- Home /
Variables that were attempted to be assessed were missing in some objects,
My script to make an object bob up and down as an effect is not working.
Hello, after being fed up that animating an object in the animation panel is not as versatile is doing an "animation" in code, I made a script that will make an object bob up and down. It worked fine until I attempted to reference another script's variable in order to tell it that my object must be matured first before it can bob up and down.
Error that I am getting (Only on the first frame when game starts):
NullReferenceException: Object reference not set to an instance of an object BobScript.Update () (at Assets/Scripts/BobScript.cs:26)
private float Bob;
private bool BobIncreasing;
public float BobSize;
public float BobSpeed;
public GameObject BobbingObject;
public string BobbingAxis;
public bool CanBob;
public TreeAI TScript;
private bool Adult;
public bool BobWhenAdult;
void Start () {
Bob = 0.8f;
}
void Update () {
if (CanBob == true) {
Adult = TScript.Adult;
if (Adult == true && BobWhenAdult == true){
if (Bob < 1 - BobSize/10) {
BobIncreasing = true;
}
if (Bob > 1) {
BobIncreasing = false;
}
if (BobIncreasing == true) {
Bob += 0.1f * BobSpeed * Time.deltaTime;
}
if (BobIncreasing == false){
Bob += -0.1f * BobSpeed * Time.deltaTime;
}
if (BobbingAxis == "X"){
BobbingObject.transform.localScale = new Vector3 (1 * Bob, 1, 1);
}
if (BobbingAxis == "Y"){
BobbingObject.transform.localScale = new Vector3 (1, 1 * Bob, 1);
}
if (BobbingAxis == "Z") {
BobbingObject.transform.localScale = new Vector3 (1, 1, 1 * Bob);
}
}
}
}
}
Answer by StormMuller · Oct 17, 2017 at 08:59 PM
Your code is difficult to read. But have you tried:
var transform.position = new Vector3(transform.position.x, Mathf.Sin(Time.time), transform.position.z);
What is this line of code for? I am not trying to move my object anywhere, the problem is that something is not set properly, and so it is equal to null when access to it is attempted.
Turns out that I was being dumb and dragged the script on some other objects and forgot. The problem with that is that I was building the script towards one specific object and not the others, so when the code ran, it got confused that there was some things that were missing on the other objects.