I have a prefab with a script to change animation clips upon mouseButtonDown.
When I instantiate many copies of it using the following code:
void InitList ()
{
for (int x = 1; x < numColumns; x++)
{
for ( int y =1; y < numRows; y++)
{
Instantiate (gridUnit, new Vector2(x,y)*spacing, Quaternion.identity);
}
}
}
I get a nice grid of this prefab, however whenever I click one of the instances, all of them change animation clips simultaneously (as if I clicked all of them…).
post your code where you check Mouse input
but i think you have done something like
void Update(){
if (Input.GetKeyDown(KeyCode.Mouse0)) {
//do something
}
}
and you are not checking if a specific object was clicked on. and if every object hast this code in where only mouse button down is checked, all will do the same as it happens for you
One is to use the IPointerClickHandler interface like so:
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class ClickableScript : MonoBehaviour, IPointerClickHandler {
public void OnPointerClick(PointerEventData eventData)
{
Debug.Log("Clicked " + gameObject.name);
}
}
Or use some type of HoveredObjectManager script that uses a raycast from the camera to store the currently hovered object. Then check the hovered object to see if it has the component you need. This script should only exist once in the scene.
Or do it all in one script:
using UnityEngine;
using System.Collections;
public class InputScript : MonoBehaviour {
public float rayDistance = 1000f;
public float LayerMask rayLayerMask;
void Update
{
if (Input.GetMouseButtonDown(0))
{
// Get hit object. If null, stop
GameObject hitObj = GetHitObject();
if (hitObj == null) return;
// Check hit object for component. If not found, stop
ChangeClipScript clipScript = hitObj.GetComponent<ChangeClipScript>();
if (clipScript == null) return;
clipScript.Change();
}
}
GameObject GetHitObject()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, rayDistance, rayLayerMask))
{
return hit.collider.gameObject;
}
else
{
return null;
}
}
}
As a beginner, this all goes over my head, but I will try to go into it further and search what I do not understand before asking any more questions.
Thanks, greatly appreciate it!