I’m new to C# and my procedural programming insights are steering me wrong.
If I create a new player, my simple FollowCamera.cs script, attached to the main camera, works fine, PROVIDED I manually drag the game object “player” onto the “target” slot of the script. I built these from demo’s and tutorials.
But what I need to do is instantiate a new player at run-time, when “drag and drop” is not available to the user.
How do I do the equivalent “drag and drop” in C#, assuming I just made a new Game Object called “localplayer”?
What does NOT work is something simple like:
FollowCamera.target = localplayer;
GameObject _player; //Assign this as your already in-game player
void Update()
{
if(_player == null) //If _player suddenly is lost
{
_player = GameObject.Find("Player"); //Search for instiated Player
}
else
{
Debug.Log("Player Is Alive!"); //Print player is alive.
}
}
Unfortunately I don’t understand “Assign this as your already in-game player”.
How does creating yet one more GameObject tell my camera script to use it as a target? I already know that a GameObject called “localPlayer” is the desired target. So, yes, I could create another GameObject called _player and put in a command such as:
_player = GameObject.Find(“localPlayer”);
But how do I get that information passed into my FollowCamera.cs script as the desired instantiation of the “target” variable?
I’m sure it’s obvious to you when you say “assign” it, but that’s the part of the whole thing I need spelled out, because it’s what I do NOT understand how to do.
I see, you already have a target selection variable in your FollowCamera. What I was doing in the other code was giving you an example of HOW to reassign the target variable to an instantiated object.
Just insert this code, below, into the Void Update part of your code.
if(target == null) //If player suddenly is lost
{
target = GameObject.Find("localPlayer") //looks for any instances (objects) of "localPlayer" in the scene
}
else
{
Debug.Log("Player Is Alive!"); //Print player is alive.
}