user8048595
user8048595

Reputation: 139

Unity-How to stop a moving object when the Camera sees it

This is just a simple thing I want to do. I have my cube gameobject rotating and I want to make it so when the camera sees the cube, it stops rotating. If you could steer me in the right direction, I'd appreciate it. thank you

public class cubeMove : MonoBehaviour, MoveObject
{
public Renderer rend;

    public void Update () {

    rend = GetComponent<Renderer>();
    stopWhenSeen();      
}
public void move()
{
    transform.Rotate(new Vector3(15, 30, 45) * Time.deltaTime);
}
public void stopWhenSeen()
{
    if (rend.enabled == false)
    {
        move();
    }
}

}

Upvotes: 0

Views: 968

Answers (2)

Hellium
Hellium

Reputation: 7346

Implement the OnBecameVisible and OnBecameInvisible MonoBehaviour's message :

private visible = false ;

// OnBecameVisible is called when the renderer became visible by any camera. INCLUDING YOUR EDITOR CAMERA
void OnBecameVisible()
{
    visible = true ;
}

// OnBecameInvisible is called when the renderer is no longer visible by any camera. INCLUDING YOUR EDITOR CAMERA
void OnBecameInvisible()
{
    visible = false;
}

void Update()
{
    if( !visible )
        move() ;
}

public void move()
{
    transform.Rotate(new Vector3(15, 30, 45) * Time.deltaTime);
}

Upvotes: 2

Doh09
Doh09

Reputation: 2385

https://docs.unity3d.com/ScriptReference/Renderer-isVisible.html

You could try the .isVisible bool in your update method.

Here is a thread with other suggestions:

http://answers.unity3d.com/questions/8003/how-can-i-know-if-a-gameobject-is-seen-by-a-partic.html

Upvotes: 0

Related Questions