TL;DR Trying to call a method on a clone returns an error.
I have a prefab called NPC, which has a script attached called pathfinder. In said script, there is a method called editTag(), which edits the tag and some private data members.
When the game starts, clones of NPC are created, and I want to called the editTag() method of each clone as soon as they are instantiated. To do this, I get the script of the clone and attempt to run the method, but hit an error: “object reference not set to an instance”.
I think when I get the script of the clone, the script does not recognise that it belongs to the clone, and does not know which data members to edit. How can I fix this issue?
Below is my relevant code:
In the spawner script:
void spawnNPCs()
{
string[] tags = new string[] { "Rock", "Scissors", "Paper" };
foreach (string tag in tags)
{
for (int i = 0; i < 50; i++)
{
GameObject clone = Instantiate(NPC, GetRandomPosition(), NPC.transform.rotation);
pathfinder pathfinderScript = clone.GetComponent<pathfinder>();
pathfinderScript.editTag(tag);
}
}
}
In pathfinder script:
public void editTag(string tag)
{
Debug.Log("Edit Tag called.");
this.tag = tag;
sr.sprite = Resources.Load<Sprite>("Sprites/" + tag);
if (tag == "Rock") { this.preyTag = "Scissors"; this.predTag = "Paper"; }
else if (tag == "Paper") { this.preyTag = "Rock"; this.predTag = "Scissors"; }
else if (tag == "Scissors") { this.preyTag = "Paper"; this.predTag = "Rock"; }
}
The editTag method does get called, and nothing seems to be null, including the returned reference to the clone, the random position, the script nor the tags.