In my game when the player uses one of their tools I instantiate the appropriate tool from a Resources folder on top of the player. I then call a function within the tool’s script to change the sprite of the tool. To have fewer scripts I wrote a single tool script with the sprites passed into a public array, so I can use the same script for each different tool.
If the tool already exists in the scene then the sprite changes just fine. But if I instantiate it from the resources folder then I get a NullReferenceException from the sprite array. But the instantiated object when inspected has the sprites declared in it’s public array.
Here is the relevant code I am using:
Player Code:
GameObject toolObject = Instantiate(Resources.Load(selectedItem.id, typeof(GameObject)), target, Quaternion.identity) as GameObject;
ToolScript toolScript = GameObject.FindGameObjectWithTag("Tool").GetComponent<ToolScript>();
toolScript.ChargeSprite(directionFacing);
Tool Script Code:
public Sprite[] sprites = new Sprite[8];
SpriteRenderer rend;
void Start()
{
rend = GetComponent<SpriteRenderer>();
}
public void ChargeSprite(string direction)
{
switch (direction)
{
case "Down": rend.sprite = sprites[1]; break;
case "Left": rend.sprite = sprites[2]; break;
case "Right": rend.sprite = sprites[5]; break;
case "Up": rend.sprite = sprites[7]; break;
}
}
Does anyone know why the sprite array is null when the object is instantiated from the resources folder, versus already in the scene?