Home > OS >  Getting script component from a clicked object
Getting script component from a clicked object

Time:02-06

I'm trying to get the script component of an object once it has been clicked by a player, then run a specific function from the script when clicked. What I want to go is ether find the script based of the clicked objects name, or just a general way of getting scripts without the class name as it changes with each script. I've looked for way to do both but none work. I may just be implementing it bad so would love some help.

CodePudding user response:

void onm ouseDown(){
 // this object was clicked - do something
 Destroy (this.gameObject);
 } 

CodePudding user response:

It really depends on what type of objects you want to catch the clicks. If it’s 2d images, make sure you have RaycastTarget bool checked and use IPointerDownHandler interface.

If you gonna do it with 3d objects, then you should add some collider component to them and than make a raycast from camera view every time player clicks.

  1. Get the ray from camera view - https://docs.unity3d.com/ScriptReference/Camera.ScreenPointToRay.html
  2. Check the raycast with existing ray, putting the result to array - https://docs.unity3d.com/ScriptReference/Physics.Raycast.html
  3. Better use separate layer for your objects so you can filter them among others
  4. Use TryGetComponent to check if collision object has your target component - https://docs.unity3d.com/ScriptReference/GameObject.TryGetComponent.html

This way is more complicated than “OnMouseDown” event, but it is more reliable and debuggable, and also it fits perfectly for good common game architectures, unlike onm ouseDown event

  •  Tags:  
  • Related