Hi,
I’m completely new to Unity and game engines in general so it may be a complete newbie question. I have a few years of C# programming behind me though.
I created a cube object in the editor and attached the following script to it:
public class preclick : MonoBehaviour
{
private GameObject clicked = null;
private bool rotating = false;
// Use this for initialization
void Start()
{
Debug.Log("Started.");
}
// Update is called once per frame
void Update()
{
if (!rotating)
{
//check if the left mouse has been pressed down this frame
if (Input.GetMouseButtonDown(0))
{
if (clicked != null)
Debug.Log("GameObject is: " + clicked.name);
else
Debug.Log("GameObject is null");
//empty RaycastHit object which raycast puts the hit details into
RaycastHit hit;
//ray shooting out of the camera from where the mouse is
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
//print out the name if the raycast hits something
clicked = hit.collider.gameObject;
rotating = true;
Debug.Log(hit.collider.name);
}
}
}
if (clicked != null)
{
clicked.transform.Rotate(Vector3.forward * Time.deltaTime * 100);
}
}
}
Basically I want the clicked object to start rotating. That works fine. I then create a prefab from that cube (by dragging it into “Assets”) and delete it from the editor window. I create a new empty gameobject and attach the following script to it:
public class startup : MonoBehaviour {
public GameObject obj;
// Use this for initialization
void Start () {
Instantiate(obj, new Vector3(0, 0, 0), Quaternion.identity);
Instantiate(obj, new Vector3(2, 0, 0), Quaternion.identity);
}
// Update is called once per frame
void Update () {
}
}
In the editor I drag the cube prefab into obj slot of the empty gameobject. Everything works, I get 2 cubes drawn on screen, side by side. HOWEVER, when I click one it starts rotating, when I click the other one, nothing happens. It seems that the “rotating” variable is already set to true and it doesn’t register the click.
It looks as if there is only one object of class “preclick” between the 2 cubes, is that correct? Shouldn’t each cube have its own instance of the preclick object?
So do I have to keep arrays of my prefab objects in the behaviour script or what is the preffered way of dealing with that?
I searched for answers but couldn’t find anything similiar to my problem. Sorry if it’s obvious