- Home /
Question by
AndrewRyan · Nov 29, 2015 at 09:53 AM ·
gameobjectinstantiatetargetfindgameobjectwithtag
How to resort to another object if one is not found?
Hi, I want the game camera to choose a target depending on if the target exists or not. Is this possible without throwing a null exception? Here is an example of what I want to do:
Transform player, camLocation;
void Awake()
{
camLocation = GameObject.FindGameObjectWithTag("CamLocation").transform;
player = GameObject.FindGameObjectWithTag("Player").transform;
if(camLocation)
Camera.main.transform.position = camLocation.position;
else if(player)
Camera.main.transform.position = player.position;
}
If a camLocation object is in the scene, it should be used as the target. When it doesn't exist, I want the camera to resort to the player as the target, etc.
Thanks!
Comment
Answer by OncaLupe · Nov 29, 2015 at 09:44 PM
You just need to check if the transform reference is null. If null after a Find, then it does not exist.
if(camLocation != null)
Camera.main.transform.position = camLocation.position;
else if(player != null)
Camera.main.transform.position = player.position;
The script doesn't store a reference for those transforms(camLocation and player) initially. It should find them on awake, but this returns an error. Is there a more elegant way of finding references dynamically?