How can I make object “B” visible when the player clicks on object “A”? I have only a single instance of an object named “B” in the scene so it would be easy to refer to it by it’s name.
So I’m trying to set the object called hotspotCylinder.001 visible/active when the player clicks on an object called Cylinder.001.
Here’s my attempt:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class objectClickerScript : MonoBehaviour {
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 150.0f))
{
if (hit.transform != null)
{
MeshCollider mc;
if (mc = hit.transform.GetComponent<MeshCollider>())
{
PrintName(hit.transform.gameObject);
}
}
}
}
}
private void PrintName(GameObject go)
{
print(go.name);
if (go.name == "Cylinder.001") {
gameObject = "hotspotCylinder.001";
gameObject.SetActive(!gameObject.activeSelf);
}
}
}
Here are two scripts that should get you moving. You can name them and refactor them to your needs. I commented as much as I could. Just put the raycaster in the scene. Add the markup script to the objects that can be clicked. Then add the reference object to be turned on, on those scripts.
using UnityEngine;
public class Raycaster : MonoBehaviour
{
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
// You could add a layer mask in this raycast to only pick out a certain layer
// Put all your clickable objects in that one layer - makes raycast a little more performant
if (Physics.Raycast(ray, out hit, 150.0f))
{
// Do we have a markup, if so, enable its linked object
Markup hasMarkup = hit.transform.gameObject.GetComponent<Markup>();
if (hasMarkup != null)
{
hasMarkup.ToggleLinkedObject();
}
}
}
}
}
using UnityEngine;
/// <summary>
/// Placed on the object that can be clicked
/// </summary>
public class Markup : MonoBehaviour
{
[SerializeField] GameObject objectToMakeVisible; // Reference object to be turned on
void Awake()
{
// we start hidden - in case we left it visible in the editor
objectToMakeVisible.SetActive(false);
}
/// <summary>
/// Toggles the visibility of the linked object
/// </summary>
public void ToggleLinkedObject()
{
objectToMakeVisible.SetActive(!objectToMakeVisible.activeSelf);
// If don't want the object to toggle, then do (comment out line above)
//objectToMakeVisible.SetActive(false);
// if the visibility only happens once, remove this script so it can't be clicked again (comment out line above)
//Destroy(this);
}
}
It’s a simple markup style system. If object has the markup script, then it can toggle an object on. Right now, it will toggle the object on/off, but I put comments in on how not to do that.
Hope this helps.