Hi, I’m trying to make an object move up when I click on it. It works fine for a single object. Then I created a prefab and added multiple instances of that object to the scene. Now when I click on one of those objects all those instances move up. Why does it happen ? I just need to move only the clicked object.
Here’s my code
if(Input.GetMouseButtonDown(0)) {
RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint((Input.mousePosition)), Vector2.zero);
if(hit.collider != null)
{
this.rb2d.velocity = Vector2.zero;
this.rb2d.AddForce(Vector3.up*ySpeed);
}
}
Thank you.
The script you attached checks if the raycast hits anything and if anything is hit the attached gameObject is moved upward. Instead, you either need to check if the hit object is the one the script is attached to or perform an action only on the hit object(s).
The first option is easier to implement, just change
if(hit.collider != null)
to
if(hit.collider != null&&hit.transform==transform)
The second option is better because it would only do one raycast per click but it would also require you to separate input management from the object script. For this you would make a new script that works like
using UnityEngine;
public class InputManager : MonoBehaviour {
public float ySpeed=1f;
void Update() {
if(Input.GetMouseButtonDown(0)) {
RaycastHit2D hit=Physics2D.Raycast(Camera.main.ScreenToWorldPoint((Input.mousePosition)), Vector2.zero);
if(hit.collider!=null) {
Rigidbody2D rb2d=hit.transform.GetComponent<Rigidbody2D>();
if(rb2d!=null) {
rb2d.velocity=Vector2.zero;
rb2d.AddForce(Vector3.up*ySpeed);
}
}
}
}
}
or, if you can hit multiple objects use Physics2D.RaycastAll instead of Physics2D.Raycast