Onbecamevisible does not work?

I have this code attached to a object:

function OnBecameVisible()

{
print(“Ping”);
}

But when I hit play and look at my object, I do not get the console message.

2 Answers

2

Stupid me, the gameobject needs a renderer in order to work, I attached it to a empty gameobject.

@Bluestrike, be aware that OnBecameVisible happens when the object enters any active camera's frustum, even if you can't actually see it - if it's behind a mountain, for instance. Since any active camera counts, if you switch from Game to Scene view while the game is running in the Editor, the Scene cam becomes active and may generate this event.

Ah ok, I am using this to trigger a random animation if the player can see this renderer. Will it fire if the object is occluded?

I attached this script to a spider yet it moves even if I do not see it with my camera. Here is my code:

using UnityEngine;
using System.Collections;

public class SpiderController : MonoBehaviour {

	//4 ahead

	public float moveSpeed;
	private bool canMove;

	private Rigidbody2D myRigidbody;

	// Use this for initialization
	void Start () 
	{
		myRigidbody = GetComponent<Rigidbody2D> ();
	}
	
	// Update is called once per frame
	void Update () 
	{
		if (canMove = true) 
		{
			myRigidbody.velocity = new Vector3 (-moveSpeed, myRigidbody.velocity.y, 0f);
		}
	}

	void OnBecameVisible()
	{
		canMove = true;
	}
}

You need to disable it when it becomes invisible with OnBecameInvisible, where you can set canMove = false