system
1
Hello everyone,
As you guessed I am a new comer about Unity and C#. I could not find a satisfying answer on the internet.
I have an object and I want to cast a ray from my camera to that object (it will have a spesific name) and that must trigger some other event.
What is the best and easy way?
I added a script to my camera like below:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraCastingScript : MonoBehaviour {
public static float DistanceFromTarget;
Camera cam;
void Start()
{
cam = GetComponent<Camera>();
}
void Update()
{
Ray ray = cam.ViewportPointToRay(new Vector3(0.5F, 0.5F, 0));
RaycastHit hit;
}
}
And I also added a script to my object like below:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SkinColorScript : MonoBehaviour {
public float TheDistance;
public GameObject SkinColorText;
// Update is called once per frame
void Update () {
TheDistance = CameraCastingScript.DistanceFromTarget;
}
private void OnTriggerEnter (Collider other)
{
if (other.name == "MyCamera")
{
if (TheDistance <= 50)
{
SkinColorText.SetActive(true);
}
else
{
SkinColorText.SetActive(false);
}
}
else
{
SkinColorText.SetActive(false);
}
}
}
I named my camera as “MyCamera”
Thanks for your assistance.
system
2
Yes exactly that is I want to provide. When ray from the camera hits the object, it deactivates the some other objects.
// CameraCastingScript.cs
using UnityEngine;
public class CameraCastingScript : MonoBehaviour
{
private Camera cam;
private IInteractionTarget lastTarget;
void Start()
{
cam = GetComponent<Camera>();
}
void Update()
{
Ray ray = cam.ViewportPointToRay(new Vector3(0.5F, 0.5F, 0));
RaycastHit hit;
// If ray hit something
if( Physics.Raycast( ray, out hit, Mathf.Infinity ))
{
// Get component to trigger
IInteractionTarget target = hit.transform.GetComponent<IInteractionTarget>();
// If object is close enough to camera, trigger it
if ( target != null && hit.distance < target.MinimumInteractionDistance )
{
if ( lastTarget != null && lastTarget != target ) lastTarget.Trigger( false );
target.Trigger( true );
lastTarget = target;
}
// If no script found, or object is too far...
else if ( lastTarget != null )
{
lastTarget.Trigger( false );
lastTarget = null;
}
}
// If no object hit...
else if ( lastTarget != null )
{
lastTarget.Trigger( false );
lastTarget = null;
}
}
}
// IInteractionTarget.cs
public interface IInteractionTarget
{
float MinimumInteractionDistance { get; }
void Trigger( bool turnOn );
}
// SkinColorScript.cs
using UnityEngine;
public class SkinColorScript : MonoBehaviour, IInteractionTarget
{
[SerializeField]
private float minimumInteractionDistance = 50;
[SerializeField]
private GameObject SkinColorText;
public float MinimumInteractionDistance
{
get { return minimumInteractionDistance; }
}
public void Trigger( bool turnOn )
{
SkinColorText.SetActive( turnOn );
}
}