I’m trying to make a prop hunt game and I made a spawning system that works, but it would require hundreds of lines of code if I added more props. Is there a way that it could look at the name of a object I’m looking at and if its a prop then search for the prefab using the name of the object so I don’t have to right a ton of code. If not, is there a way similar to this? My current code is just for one object right now, but I thought I should include it with this.
using UnityEngine;
using System.Collections;
public class Raycast : MonoBehaviour {
private GameObject brick = null;
public Transform player;
public GameObject character;
void Start () {
brick = GameObject.Find("tran(Clone)");
}
void Update () {
Ray ray = camera.ViewportPointToRay(new Vector3(0.5F, 0.5F, 0));
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
print("I'm looking at " + hit.transform.name);
else
print("I'm looking at nothing!");
if (hit.transform.name == "tran(Clone)") {
if (brick.tag == "Prop")
{
if (Input.GetKeyDown ("e")) { //Gets key "E"
GameObject clone = (GameObject)Instantiate (brick, player.position, player.rotation);
clone.transform.parent = character.transform;
Destroy (GameObject.Find("Graphics"));
rigidbody.isKinematic = false;
}
}
}
}
}
An easy way is to maintain a map of prefabs.
I’m using a scriptable object here. You’ll either have to figure out how to create one (Google is your friend) or make it a MonoBehaviour.
Raycasts are expensive so you should avoid doing it every frame unless you know it’s needed.
public class PrefabLookup : ScriptableObject
{
[SerializeField]
GameObject [] prefabs;
Dictionary<string, GameObject> prefabMap = new Dictionary();
void OnEnable()
{
foreach(GameObject go in prefabs)
{
if ( go != null)
{
if ( prefabMap.Contains(go.name)
{
Debug.LogWarning("You shouldn't have duplicate names",go);
Debug.LogWarning("You shouldn't have duplicate names",prefabMap[go.name]);
}
prefabMap[go.name] = go;
prefabMap[go.name+"(Clone)"] = go; //hack to find clones
}
}
}
GameObject GetPrefab(string name)
{
GameObject ret;
prefabMap.TryGetValue(name, out ret);
return ret;
}
}
public class Raycast : MonoBehaviour {
[SerializeField]
PrefabLookup prefabLookup = null;
void Update () {
Ray ray = camera.ViewportPointToRay(new Vector3(0.5F, 0.5F, 0));
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
print("I'm looking at " + hit.transform.name);
GameObject prefab = prefabLookup.GetPrefab(hit.transform.name);
if (prefab != null && //if it is a prefab in the list
brick.tag == "Prop")
{ //then do something...
if (Input.GetKeyDown ("e")) { //Gets key "E"
GameObject clone = (GameObject)Instantiate (brick, player.position, player.rotation);
clone.transform.parent = character.transform;
Destroy (GameObject.Find("Graphics"));
rigidbody.isKinematic = false;
}
}
}
else
print("I'm looking at nothing!");
}
}