How to access Prefab via GameObject var in runtime

Hello everyone,

I wondering how it’s possible in my C# script to access a prefab via a gameobject variable.

To explain:
I have a prefab, with a public Gameobject Variable. In the editor I set my prefab to my variable (so I set itself). Here, every thing’s fine.

But at runtime, when my prefab is spawned on the map, my Gameobject Variable is not anymore my prefab but an instance (basically it refer to itself on the map).

How Can I keep my Gameobject Variable refer to the prefab and not to this new instance?
Can you provide me a script example to show me how to proceed? (I’m not very skill, I’m just using variable, and not so much scripting).

Thanks in advance,
Have a good one!

public GameObject prefab;
public GameObject clone;

void Start (){
    clone = (GameObject)Instantiate(prefab);
    clone.GetComponent<MyScript>().myVariable = 14;
}

You now have references to both your prefab and your new GameObject. Enjoy.

A prefab is a template, a cookie cutter for a game object that takes the shape and has attributes and properties that you control, it is a mold for game objects. When a prefab has scripts attached to it then there are properties that are inherited to deal with the instance that you instantiate. I would suggest you check out the documentation on prefabs and go through the learning tutorials.

UA is not the place for asking for scripts, you do need to have a general understand of the make up of the unity engine and the concepts behind it. This is specifically why there is a manual and luckily, video tutorials to help you in your journey. Any script that is given to you will end up creating more questions, you must learn the fundamentals, otherwise you will be back time and time again… you will get frustrated by not gaining power over the creation of your project.

Further more, if you have a script that has variables of say type GameObject and in the inspector you assign prefabs to those GameObject variables, you can instantiate a copy of your prefabs through the Instantiate call in the script.