I’m making a game where the player can interact with objects, but I need to be able to determine what object the player interacted with so that I don’t call a script that the object doesn’t have. For example, here is my player’s script:
using UnityEngine;
using System.Collections;
public class PlayerControls : MonoBehaviour {
void Start () {
}
void Update () {
//Create a ray to see where the player is selecting
Ray ray = Camera.mainCamera.ScreenPointToRay(Input.mousePosition);
Debug.DrawRay(ray.origin, ray.direction, Color.yellow);
RaycastHit selectedObject;
//Check to see if the player interacts with something
if (Input.GetButtonDown("Interact")){
if (Physics.Raycast(ray, out selectedObject)){
InteractWith(selectedObject.transform);
}
}
}
private void InteractWith(Transform selectedObject){
switch(selectedObject.name){
case "Chest":
ChestBehavior script = selectedObject.GetComponent<ChestBehavior>();
script.OnInteract();
break;
case "Some other object":
//Call some other script
break;
case "etc.":
//etc.
break;
}
}
}
Notice the part that says “switch(selectedObject.name)”? On a small scale, this works just fine, but in a bigger project, I’m going to want to place multiple “Chest” objects in one room, and if they all have the same name it will be hard to know which chest is which in the hierarchy. Instead of testing for selectedObject.name, is there a way to test for something like selectedObject.prefabName?
Please don't post comments as answers. Post comments by clicking the [add new comment] button, a window then open for you to type in. Here at Unity Answers, Answer means Solution, not Response.
– AlucardJayIndeed, in every script that has that function, and i am pretty sure there is a version of that function that calls the function in the gameobject plus its children. But that is only one of the methods. The general idea is to use a script shared on all objects to determine what is what, instead of names.
– Professor_Snake