The first thing to start with is making a script that will hold the Prefabs as a variable. This can be a new script, or in better practise - A game manager script.
You will need to attach this script to a GameObject and it must inherit MonoBehaviour. I’ll provide an example in C#.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class makesThings : MonoBehaviour {
public GameObject _myPrefab;
}
In the inspector, you should now see a variable called _myPrefab. Select your Prefab, or simply drag it over the crosshair. You will then be able to reference this prefab and Instantiate it as follows;
using UnityEngine;
using System.Collections;
public class makesThings : MonoBehaviour {
public GameObject _myPrefab;
void letsMakeThings () {
GameObject _newThing = (GameObject)Instantiate(_myPrefab);
}
}
Now I am assuming the prefab has a script attached to it? You can access this script, and subsequently any public variables in that script as follows;
Lets assume the script is called “MyScript”.
using UnityEngine;
using System.Collections;
public class makesThings : MonoBehaviour {
public GameObject _myPrefab;
void letsMakeThings () {
GameObject _newThing = (GameObject)Instantiate(_myPrefab);
MyScript _scriptInstance = (MyScript)_newThing.GetComponent("MyScript");
}
}
Now its important to note the following;
MyScript _scriptInstance
The first “MyScript” is a TYPE declaration, that is - you are declaring the variable as a type of the class “MyScript”.
(MyScript)_newThing.GetComponent("MyScript")
The first MyScript here is a cast, to ensure it returns the component as the correct type. It is good practise to always cast like this.
The second “MyScript” is simply the name of the script as a string. Do not put a TYPE here as it will not work.