Search Unity

create gameobject via script and change it's color doesn't work

Discussion in 'Scripting' started by Druidenhorst, May 4, 2019.

  1. Druidenhorst


    Sep 17, 2016
    I create a GameObject with a prefab:
    Code (CSharp):
    1. GameObject cube_prefab = (GameObject)Resources.Load("FiniteElement", typeof(GameObject));
    2. GameObject new_cube = Instantiate(cube_prefab,new Vector3(x,y,0),Quaternion.identity);
    3. FinitElement fe = new_cube.GetComponent<FinitElement>(); // get the script of the instantiated object
    4. fe.setBaseType(FinitElement.BaseType.core); // call the method of the script (this works, I tested it with print())
    After creating, I have to declare some variables of this instantiate, e.g. the "BaseType". I don't want to do this directly, but with a method. The reason is that later I can center other things in this methods, e.g. changing the material at the same moment.

    The Method in the Script, which is attached on the prefab is:
    Code (CSharp):
    1. public class FinitElement : MonoBehaviour
    2. {
    3.   public enum BaseType {core, rock, soil, water, air}
    4.   public BaseType myBaseType = BaseType.air;
    5.   private Renderer myRenderer;
    6.   void Start()
    7.   {
    8.     myRenderer = GetComponent<Renderer>();myRenderer.material.color = Color.yellow;
    9.   }
    10.   public void setBaseType(BaseType _BaseType)  // <- this is the method
    11.   {
    12.     myBaseType = _BaseType;
    13.     myRenderer.material.color = Color.yellow; // for testing just a test with the material color
    14.   }
    15. }
    I get an error " NullReferenceException: Object reference not set to an instance of an object FinitElement.setBaseType (BaseType _BaseType)"
    Which is produced by the last lin in void setBaseType: myRenderer.material.color = Color.yellow;.
    If I comment this out, the engine starts - but of course not with the needed effect.
    I can't figure out, what is wrong with my attempt to save the Renderer in myRenderer and acessing it later in the method setBaseType.
    Can anyone give me a hint?
  2. GroZZleR


    Feb 1, 2015
    Most likely setBaseType is being called before Start() has been called, so myRenderer is null. That, or you don't have a renderer component attached to this particular GameObject.
  3. Druidenhorst


    Sep 17, 2016
    Thanks, the first suggestion was right! I changed Start() to Awake() and it worked!
    GroZZleR likes this.