Action set to null when doing GetComponent
Hello!
I'm creating a Tile class that has an Action member. To spawn a tile I want to pick them from "templates" which I create in a function in MapController like this.
registerTile("Yellow_Tile", () =>
{
//Insert function here
});
And registerTile:
public void registerTile(string name, Action onCollision)
{
GameObject go = GameObject.Instantiate(Resources.Load(name, typeof(GameObject))) as GameObject;
Tile t = go.AddComponent<Tile>();
t.init(onCollision);
tiles.Add(go);
}
When I spawn a tile I simply do this:
GameObject go = GameObject.Instantiate(tiles[index], new Vector3(x,y,z), Quaternion.identity) as GameObject;
However this sets my Action member of Tile to null.
How do I copy this Action member into the go GameObject's Tile Component?
(I realise this probably has something do do with the innner workings of Action in c# that I've misunderstood)
Thank you in advance!
Answer by TritZium · Feb 28, 2016 at 03:05 PM
The problem was that the GameObject being loaded already had a Tile Component. Otherwise this was the coorect approach. (I simply changed from AddComponent() to GetComponent().
Your answer
![](https://koobas.hobune.stream/wayback/20220612065332im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to get a variable value before it was null ? 2 Answers
if (gameobject != null) giving UnassignedReferenceException 2 Answers
Variable Becoming null only inside functions 2 Answers
How do i fix "Edge.fromNode is null" and "Removing null node" 0 Answers
How to fix MissingReferenceException? 0 Answers