- Home /
Coding equivalent of Draging an Object into the Inspector (Solved)
I've been using a very simple script to make my main camera follow my player object through the scene. Unfortunately I've hit a problem which should have been obvious but I overlooked.
The script uses the variable 'target' and you drag the target into the inspector to assign it. All is good until my playerObject changes (the player objects are vehicles and at times within a scene your vehicle can change)
And herein lies my problem... once I destroy one playerObject/vehicle and instantiate another in its place the 'target' variable no longer has anything assigned to it and stops following the player.
using UnityEngine;
using System.Collections;
public class FollowPlayerCSharp : MonoBehaviour
{
public Transform target;
public float distance;
void Update()
{
transform.position =new Vector3(target.position.x, target.position.y+25, target.position.z - distance);
}
}
The only way I can think of doing it is to make the camera follow a certain 'Tag' but how do I make the target variable the tag name (or assign the tag name to my target variable)
???
This script is attached to your main camera? The FollowPlayerCSharp
script?
Answer by steakpinball · Mar 20, 2015 at 06:28 PM
The coding equivalent of dragging an object into a field is assigning it.
void Update() {
if (!target) {
// Search for object with Player tag
var go = GameObject.FindWithTag("Player");
// Check we found an object with the player tag
if (go)
// Set the target to the object we found
target = go.transform;
}
if (target)
transform.position =new Vector3(target.position.x, target.position.y+25, target.position.z - distance);
}