So i’m working on a game where we have you lay down tiles and objects in the game to help get through the level. Right now we’re experimenting with having a couple GUItextures along the side of the screen, each with a script tied to them and having a single instantiation script that they talk to. Then when you click on the GUI’s on the side it will change the variable in the instantiation script, I.E. changes from instantiating cubes to spheres, and so then you can lay an object to guide you or one to clear a path. Now i used a debug log in an update function in the instantiation script to tell me what the variable was. The problem was the variable was changing in the inspector when I looked at it, but the Log kept telling me the same object, so like the variable on the object with the instantiation script would cycle: cube,sphere, cylinder, but it would only tell me the variable was cube the whole time in game. Aside from only telling me the object didn’t change, the object that was instantiated stayed the same. But when I would stop the game and restart it, whatever object it ended on, say cube, would be the new variable and would only instantiate that the whole time until you stop it again.
using UnityEngine;
using System.Collections;
public class Instantiator : MonoBehaviour
{
public Transform Cheese;
public Transform Location;
private Button1 button1;
private Button2 button2;
private Button3 button3;
void Start()
{
button1 = GameObject.FindGameObjectWithTag("Button1").GetComponent<Button1>();
button2 = GameObject.FindGameObjectWithTag("Button2").GetComponent<Button2>();
button3 = GameObject.FindGameObjectWithTag("Button3").GetComponent<Button3>();
}
void Update()
{
Debug.Log (Cheese);
}
void OnMouseDown()
{
Instantiate(Cheese, Location.position, Location.rotation);
Debug.Log (Cheese);
}
}
Now here’s the code I have to tell the instantiator to change the variable, there’s two others but they’re the exact same as this except being on different GUI’s so they’re a different “Button” and different variable for transform. The “CB” is merely my way of making it easy for Unity to access the object instead of using a “Find”. I dragged the object with the instantiation script into the “CB” slot so that’s where it looks immediately for the script.
using UnityEngine;
using System.Collections;
public class Button1 : MonoBehaviour
{
public Transform Cube;
private Instantiator instantiator;
public Transform CB;
void Start ()
{
instantiator = CB.GetComponent<Instantiator>();
}
void OnMouseDown ()
{
instantiator.Cheese = Cube;
}
}