I’m working on a stealth game where there are multiple enemies in the scene - each with a vision cone.
So, what I want is to right click on an enemy to reveal his vision cone (a child), and disable any other vision cone gameobjects activated at that time. In other words, only one vision cone object can be active in the scene at a time
Cannot seem to find any reference for this - any suggestions, pointers would be greatly appreciated? Thanks in advance.
It is simple using an array of GameObjects.
Make a new Gameobject at the root of Hierarchy and attach a new script to it called “VisionCones.cs”. Inside VisionCones.cs -
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class VisionCones : MonoBehaviour
{
public GameObject[] EnemyVisionCones;
public static VisionCones instance;
private void Awake()
{
instance = this;
}
public void ActivateConeDisableOthers(GameObject ParentEnemyObject)
{
foreach (GameObject VisionCone in EnemyVisionCones)
{
VisionCone.SetActive(false);
}
ParentEnemyObject.transform.GetChild(0).gameObject.SetActive(true); // Assuming the Vision Cone GameObject is the first child of it's parent Enemy GameObject, hence the "0" in GetChild(0)
}
}
Now create and attach a new script to each of your Enemy Parent GameObjects called “VisionConeClick.cs” -
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class VisionConeClick : MonoBehaviour
{
void OnClick()
{
VisionCones.instance.ActivateConeDisableOthers(this.gameObject);
}
}
Finally add a new event click on all of your Enemy GameObjects by adding OnClick() method from the their attached VisionConeClick.cs.
Let me know if this works or you have any more questions.
Got it to work! There was an error with my code
Replaced this
if (Physics.Raycast(ray, out hit, 100f, coneMask))
{
ViewconeManager.instance.ActivateConeDisableOthers(this.gameObject);
Debug.Log("Clicked"); // to check whether we register a click
}
With this
if (Physics.Raycast(ray, out hit, 100f, coneMask))
{
if (hit.collider.gameObject == this.gameObject)
ViewconeManager.instance.ActivateConeDisableOthers(this.gameObject);
}
Worked like a charm! Thanks so much, man! Much, mc