- Home /
Question by
genzm · Sep 30, 2013 at 01:44 PM ·
instantiatecolorhighlightpipe
changing material color through C# script
Hi, The question is pretty clear. I thought it was just renderer.material.color
But somehow the color doesn't change. Here is what I've got:
I started with a puzzle, which contains several pieces (or in this case pipes). The start function of this puzzle is:
// Use this for initialization
void Start()
{
blocks = new GameObject[Size, Size, Size];
for (int x = -Size / 2; x < Size / 2; ++x)
{
for (int y = -Size / 2; y < Size / 2; ++y)
{
for (int z = -Size / 2; z < Size / 2; ++z)
{
GameObject o = (GameObject)Instantiate(Block, new Vector3(x, y, z), Quaternion.identity);
Pipe p = (Pipe)o.GetComponent(typeof(Pipe));
p.PipeModel = PipeTypes[Random.Range(0, PipeTypes.Count)];
p.pipeColor = PipeColors[Random.Range(0, PipeColors.Count)];
o.transform.parent = this.gameObject.transform;
blocks[x + (Size/2), y + (Size/2), z + (Size/2)] = o;
}
}
}
}
The pipe class looks like this:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Pipe : MonoBehaviour {
private PipeState state;
private GameObject instance;
private Color pipeColorHighlighted;
public PipeState State
{
get { return state; }
set
{
state = value;
setStyle();
}
}
private GameObject _pipeModel;
public GameObject PipeModel
{
get { return _pipeModel; }
set {
_pipeModel = value;
instance = (GameObject)Instantiate(_pipeModel);
instance.transform.parent = this.transform.parent;
instance.transform.position = this.transform.position;
}
}
public Color blockColor = new Color(0.2F, 0.3F, 0.4F, 0.0F);
public Color pipeColor;
// Use this for initialization
void Start () {
pipeColorHighlighted = Color.red; // default test color
State = PipeState.Default;
}
// Update is called once per frame
void Update () {
// respond to clicking etc...
}
private void setStyle()
{
if (state == PipeState.Highlighted)
{
print(pipeColorHighlighted);
instance.renderer.material.color = pipeColorHighlighted;
}
else
{
instance.renderer.material.color = pipeColor;
}
//instance.renderer.material.color = (state == PipeState.Highlighted) ? pipeColorHighlighted : pipeColor;
}
}
public enum PipeState
{
Default,
Highlighted,
Hovered,
Selected
}
So far everything looks right. The pipes all get their correct color. But than, when I want several pipes to be hightlighted, I use this function:
private void setHighlighted()
{
for (int i = 0; i < puzzle.Size; ++i)
for (int j = 0; j < puzzle.Size; ++j)
for (int k = 0; k < puzzle.Size; ++k)
puzzle.getBlock(i, j, index).State = k == index ? PipeState.Highlighted : PipeState.Default;
}
But somehow this doesn't change anything. The colors just stay the same. I gues the problem is somewhere in the instantiation of the pipe objects. But I can't really find it.
Thanks for the help
Comment