- Home /
Destroy GameObject behind the Main Camera
Hi guys,
I made 1 straight road where the character with Main Camera moves only forward. What I'm trying to do is to destroy all the objects behind the Main Camera without using Occlusion Culling.
Someone knows how to do that?
Please help.
Thanks in advance
Answer by Eric5h5 · Oct 16, 2013 at 03:05 AM
Depending on how your game actually works, put this script on each object:
function OnBecameInvisible () {
Destroy (gameObject);
}
Answer by whydoidoit · Oct 16, 2013 at 01:25 AM
Yep:
//Presuming you have the item to be tested in a variable called "item"
float distanceToCull = 4f;
var cameraPosition = Camera.main.transform.position;
var vectorToItem = (item.position - cameraPosition);
if(Vector3.Angle(vectorToItem, Camera.main.transform.forward) > 90) //It's behind us
{
//Perhaps ensure it's far enough away
if(vectorToItem.sqrMagnitude > distanceToCull * distanceToCull)
{
//Kill it
}
}
Unity gives me an error. I tried a lot. But nothing helps. Can you help me please?
This is the error
Assets/Scripts/scr_s1ingame/level04/NewBehaviourScript.js(1,6): UCE0001: ';' expected. Insert a semicolon at the end.
This is the code
float distanceToCull = 4f;
var cameraPosition = Camera.main.transform.position;
var vectorToItem = (item.position - cameraPosition);
if(Vector3.Angle(vectorToItem, Camera.main.transform.forward) > 90) //It's behind us
{
//Perhaps ensure it's far enough away
if(vectorToItem.sqr$$anonymous$$agnitude > distanceToCull * distanceToCull)
{
//$$anonymous$$ill it
}
}
The error is in this line
float distanceToCull = 4f;
Ok I found it. It's
var distanceToCull : float = 4f;
I added a var into this js
var item : Transform;
And when I attach the item to the var in the inspector Unity gives me this error
UnityException: You are not allowed to call this function when declaring a variable. $$anonymous$$ove it to the line after without a variable declaration. If you are using C# don't use this function in the constructor or field initializers, Ins$$anonymous$$d move initialization to the Awake or Start function. UnityEngine.Component.get_transform () (at C:/BuildAgent/work/7535de4ca26c26ac/Runtime/ExportGenerated/Editor/UnityEngineComponent.cs:21) NewBehaviourScript..ctor () (at Assets/Scripts/scr_s1ingame/level04/NewBehaviourScript.js:5)
Your answer
Follow this Question
Related Questions
Pick up objects 2 Answers
Dispose Object in IOS 0 Answers
Destroy the current GameObject? 7 Answers
How to remove an object from an array once it has been destroyed 1 Answer