2016-07-21 5 views
0

Моя идея состояла в том, чтобы создать цветной lerp в моей игре. У меня есть стек, и каждый новый порожденный объект должен появляться с другим цветом. К сожалению, я не знаю, как применить это в стеке.Unity C# Создавать с GetComponent в стеке?

Мой код:

private void ColorMesh(Mesh mesh) 
{ 
    Vector3[] vertices = mesh.vertices; 
    Color32[] colors = new Color32[vertices.Length]; 

    float f = Mathf.Sin(Time.deltaTime * 0.25f); 

    for (int i = 0; i < vertices.Length; i++) 
     colors[i] = Lerp4(gameColors[0], gameColors[1], gameColors[2], gameColors[3], f); 
    mesh.colors32 = colors; 
} 

private Color32 Lerp4(Color32 a, Color32 b, Color32 c, Color32 d, float t) 
{ 
    if (t < 0.33f) 
     return Color.Lerp(a, b, t/0.33f); 
    else if (t < 0.66f) 
     return Color.Lerp(b, c, (t - 0.33f)/0.33f); 
    else 
     return Color.Lerp(c, d, (t - 0.66f)/0.66f); 
} 

public void CreateTiles(int amount) 
{ 
    for (int i = 0; i < amount; i++) 
    { 
     //Creates a tile and adds it to the stack 
     tileEmpty.Push(Instantiate(tilePrefabs[0])); 
     tileEmpty.Peek().name = "TileEmpty"; 
     tileEmpty.Peek().SetActive(false); 
    } 

Как я теперь применить изменение цвета? Я знаю, что это должно быть после tileEmpty.Push ... в моем цикле for, но как? Все, что я пробовал с GetComponent<MeshFilter>().mesh;, не работало ... Все мои порожденные объекты имеют один и тот же цвет.

Мой полный сценарий выглядит следующим образом.

using UnityEngine; 
using System.Collections; 
using System.Collections.Generic; 

public class SpawnScript : MonoBehaviour 
{ 

    public Color32[] MColors; 

    public GameObject[] tilePrefabs; 
    public GameObject currentTile; 

    private static SpawnScript instance; 

    private Stack<GameObject> tileEmpty = new Stack<GameObject>(); 
    public Stack<GameObject> TileEmpty 
    { 
     get { return tileEmpty; } 
     set { tileEmpty = value; } 
    } 

    public static SpawnScript Instance 
    { 
     get 
     { 
      if (instance == null) //Finds the instance if it doesn't exist 
      { 
       instance = GameObject.FindObjectOfType<SpawnScript>(); 
      } 

      return instance; 
     } 
    } 

    void Start() 
    { 


     //Creates 100 tiles 
     CreateTiles(20); 

     //Spawns 50 tiles when the game starts 
     for (int i = 0; i < 10; i++) 
     { 
      SpawnTile(); 
     } 

    } 

    public void CreateTiles(int amount) 
    { 

     for (int i = 0; i < amount; i++) 
     { 

      GameObject Tile = Instantiate<GameObject>(tilePrefabs[0]); 

      //Creates a tile and adds it to the stack 
      tileEmpty.Push(Tile); 
      // ColorMesh(tilePrefabs[0].transform.GetChild(0).GetComponent<MeshFilter>().sharedMesh); 
     //With this all tiles have the same color 

      //Sets the name of the visibility of the tiles 
      tileEmpty.Peek().name = "TileEmpty"; 
      tileEmpty.Peek().SetActive(false); 
     } 
    } 

    public void SpawnTile() 
    { 
     //If we are out of tiles, then we need to create more 
     if (tileEmpty.Count == 0) 
     { 
      CreateTiles(10); 
     } 

     //Generating a random number between 0 and 1 
     //I am using this because I want to add an other tile later 
     int randomIndex = Random.Range(0, 1); 
     if (randomIndex == 0) //If the random number is one then spawn a left tile 
     { 
      GameObject tmp = tileEmpty.Pop(); 
      tmp.SetActive(true); 
      tmp.transform.position = currentTile.transform.GetChild(0).transform.GetChild(0).position; 
      currentTile = tmp; 
     } 
    } 

    public void ColorMesh(Mesh mesh) 
    { 
     Vector3[] vertices = mesh.vertices; 
     Color32[] colors = new Color32[vertices.Length]; 

     float f = Mathf.Sin(Time.deltaTime * 0.25f); 

     for (int i = 0; i < vertices.Length; i++) 
      colors[i] = Lerp4(MColors[0], MColors[1], MColors[2], MColors[3], f); 
     mesh.colors32 = colors; 
    } 

    public Color32 Lerp4(Color32 a, Color32 b, Color32 c, Color32 d, float t) 
     { 
      if (t < 0.33f) 
       return Color.Lerp(a, b, t/0.33f); 
      else if (t < 0.66f) 
       return Color.Lerp(b, c, (t - 0.33f)/0.33f); 
      else 
       return Color.Lerp(c, d, (t - 0.66f)/0.66f); 
     }  
} 

Эта линия проблема:

ColorMesh(tilePrefabs[0].transform.GetChild(0).GetComponent<MeshFilter>().sharedMesh); 
+1

Крис, есть причина, вы обманываете с сеткой ??! Все, что вы делаете, чтобы изменить цвет объекта, это изменить его .color ...?!?! – Fattie

+0

https://youtu.be/lWFp8Qy9BD8 Возможно, это помогает понять, что я пытаюсь. Я пытаюсь изменить цвет гладко на другой цвет каждый раз, когда я создаю объект – ChrisD

+0

'MeshFilter' is ** НЕ ** отвечает за цвет. 'MeshRenderer' есть. См. Ответ Ю Лю. –

ответ

1

enter image description here

using UnityEngine; 
using System.Collections; 

public class CubeGenerate : MonoBehaviour { 

    public GameObject MCube; 
    public Stack MCubeStack = new Stack(); 
    public Color[] MColors; 
    public int MCubeCount; 

    private int _mColorCount 
    { 
     get 
     { 
      return MColors.Length; 
     } 
    } 
    // Use this for initialization 
    void Awake() { 
     StartCoroutine(GenerateCube()); 
    } 

    IEnumerator GenerateCube() { 
     for (int i = 0;i< MCubeCount; i++) 
     { 
      GameObject Cube = Instantiate<GameObject>(MCube); 
      Cube.GetComponent<MeshRenderer>().material.color = Lerp4(MColors[0], MColors[1], MColors[2], MColors[3],i); 
      Cube.name = i.ToString(); 
      Cube.transform.position = new Vector3(0f, 0.25f * i, 0f); 
      MCubeStack.Push(Cube); 
      yield return new WaitForEndOfFrame(); 
     } 
    } 

    private Color32 Lerp4(Color32 a, Color32 b, Color32 c, Color32 d, int t) 
    { 
     float r = (float)(_mColorCount - 1); 

     if (t <= MCubeCount/r) 
      return Color.Lerp(a, b, (float)t/r); 
     else if (t < MCubeCount/r * 2f) 
      return Color.Lerp(b, c, (t - MCubeCount/r)/3f ); 
     else 
      return Color.Lerp(c, d, (t - MCubeCount/r * 2f)/(_mColorCount - 1)); 
    } 
} 
+1

Извините за мой формат ошибки и мой плохой английский. Это мой первый раз использовать Stackoverflow. –