- Home /
Unable to change a variable from another script.
Hi,
I have a script (called orbitTank) with the following code:
public override void OnStartLocalPlayer() { Debug.Log("Hi!"); GetComponent().setTarget(gameObject.transform); }
The debug log is definitely printed it out. However, I still get the error, that:
The script I am trying to modify is called Orbit, which contains the following code:
using UnityEngine;
using System.Collections;
public class Orbit : MonoBehaviour
{
public float turnSpeed = 4.0f;
public Transform playerTransform;
private Vector3 offset;
private Vector3 offset2;
void Start()
{
offset = new Vector3(0, 2.5f, 6);
}
void LateUpdate()
{
//if (playerTransform == null) return;
{
offset = Quaternion.AngleAxis(Input.GetAxis("Mouse X") * turnSpeed, Vector3.up) * offset;
transform.position = playerTransform.position + offset;
transform.LookAt(playerTransform.position);
}
}
public void setTarget(Transform target)
{
playerTransform = target;
}
}
I'm not sure why this isn't working. Is anybody able to help?
Answer by slavo · Nov 28, 2016 at 11:36 AM
Hi,
when is function OnStartLocalPlayer() called? Maybe everything is working fine, but Orbit late update function is called before you set playerTransform, if OnStartLocalPlayer() is for some reason delayed.
You can find out by putting
Debug.Log(Time.timeSinceLevelLoad);
in your LateUpdate and setTarget functions.
Answer by aditya007 · Nov 28, 2016 at 12:29 PM
The error is telling you that the public Transform variable playerTransform
hasn't been assigned in the inspector. Select the object on which this script is attached, and assign a Transform value to playerTransform
variable.
On another note, I don't think GetComponent()
is called like that. At the very least, it expects a type, which you want to Get.
Therefore, change GetComponent()
to GetComponent<Orbit>()
, assuming both scripts are attached to the same GameObject.
Your answer
