Hey,
I create a GameObject with a prefab:
GameObject cube_prefab = (GameObject)Resources.Load("FiniteElement", typeof(GameObject));
GameObject new_cube = Instantiate(cube_prefab,new Vector3(x,y,0),Quaternion.identity);
FinitElement fe = new_cube.GetComponent<FinitElement>(); // get the script of the instantiated object
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:
public class FinitElement : MonoBehaviour
{
public enum BaseType {core, rock, soil, water, air}
public BaseType myBaseType = BaseType.air;
private Renderer myRenderer;
void Start()
{
myRenderer = GetComponent<Renderer>();myRenderer.material.color = Color.yellow;
}
public void setBaseType(BaseType _BaseType) // <- this is the method
{
myBaseType = _BaseType;
myRenderer.material.color = Color.yellow; // for testing just a test with the material color
}
}
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?