- Home /
How to instantiate an object with scripts?
I have a button that I press to instantiate a clone/prefab of the orginal object then when I click again it places the clone. When I instantiate the object it doesn't have any idea what scripts to use because I would have to drag the scripts I want to use into the public variable boxes at the bottom of the script. It is showing them as NULL and I cannot put the scripts into the prefab at all. Why can't I and how would I be able to communicate this clone with other scripts so it can do things based off other scripts? Normally I just use public variables and drag and drop the gameobject that has the script into the boxes but how could I reference a certain script without doing that so the clone already knows what scripts it will be using. Thanks for helping!!!
public class BuildingClickGUI : MonoBehaviour {
public BuildingScript B2; //This is NULL when object is cloned
public Buildinginfo B; //This is NULL when object is cloned
public void OnMouseDown()
{
if (B.IsHQ2 == true) {
Debug.Log ("HQ - 2nd Button");
}
Answer by Axtrainz · Nov 06, 2016 at 11:52 PM
To gain access to other script that other objects has you do this.
There's 2 ways:
Way 1: Only works if the script you want is on only 1 object.
public BuildingScript B2;
private void SomeCasualFunction()
{
//Assign to B2 that script
B2 = GameObject.FindObjectOfType<BuildingScript>();
// Use any field, function of that script
B2.name = "Yoohoo";
}
Way 2: If the Script is in more than 1 Object & you want only from one specific object then:
public BuildingScript B2;
private void SomeCasualFunction()
{
//Assign to B2 that script
B2 = GameObject.Find("ObjectName").GetComponent<BuildingScript>();
// Use any field, function of that script
B2.name = "Yoohoo";
}
Your answer
Follow this Question
Related Questions
prefab is null when I try to instantiate from another script 1 Answer
FileStream/BinaryFormatter save static variables without PlayerPrefs 1 Answer
Bullet Prefab spawning in multiple random positions and rarely the correct one (Unity 3D) 1 Answer
Struggling with Instatiating a prefab 2 Answers
Variable not Assigned 1 Answer