Change Prefab values before instantiating

Hi, so currently I’m looking at a custom marking system. The player determines what icon they want to place, and it spawns. While I’ve got all the code I need for indexing the collections, and spawning the icon… I’m not sure how to change sprite prefab values before spawning it.

Let me amend your way of thinking just a tiny bit:

  • you don’t want to change it BEFORE spawning it. Doing so would change the prefab on disk. That’s wrong and will fail in builds.

  • you want to spawn it (called “Instantiate” in Unity) and then immediately change it

So it would look something like:

public GameObject MyPrefab;  // dragged in via inspector

and to make it:

GameObject copy = Instantiate<GameObject>(MyPrefab);
// now use copy to :
// GetComponent the script you want
// change the properties you want

Also, rather than using a GameObject reference, it MAY prove useful to you to put a script of your own on the root.

If that script was called MyScript, then the above becomes:

public MyScript MyPrefab;  // dragged in via inspector

and the instantiate becomes:

MyScript copy = Instantiate<MyScript>(MyPrefab);
// now just use copy directly to set properties in the MyScript instance you just made