- Home /
Increasing speed variable from another script not working
I have a game object (tractor) with an animation. The animation speed is 1.
I have another game object (Change Speed Button) that will increase that speed by .01f every second in the update method. The speed of the "tractor" does not increase over time. If i set the speed in the Start method to say 30 it changes the speed just fine.
How can i change it in the update method?
Tractor Script
using UnityEngine;
using System.Collections;
public class SpeedController : MonoBehaviour {
private Animator anim;
public float speed;
public GameObject tractor;
void Start () {
anim = gameObject.GetComponent<Animator>();
anim.speed = speed;
}
}
Change Speed gameobject (will be a button eventually)
using UnityEngine;
using System.Collections;
public class ChangeSpeedonSpeedController : MonoBehaviour
{
private float speed = 0.0f;
SpeedController playerScript;
GameObject thePlayer;
void Start()
{
thePlayer = GameObject.Find("TractorTest");
playerScript = thePlayer.GetComponent<SpeedController>();
// playerScript.speed = 50.0f;
}
void Update()
{
Debug.Log("space" + speed);
speed = speed += 0.01f;
playerScript.speed = speed;
}
}
Answer by slavo · Dec 21, 2016 at 01:42 PM
It because you change speed of your SpeedController correctly, but you do not set it to animator then, as this is just happening in your Start. You have to add it in update so it is always up to date.
public class SpeedController : MonoBehaviour {
private Animator anim;
public float speed;
public GameObject tractor;
void Start()
{
anim = gameObject.GetComponent<Animator>();
}
void Update()
{
anim.speed = speed;
}
}
Answer by ASPePeX · Dec 21, 2016 at 03:00 PM
You just change the variabel in the script but not the animator. You can directly access the Animator from your ChangeSpeedonSpeedController script, just like you did in the SpeedController script.
using UnityEngine;
public class ChangeSpeedonSpeedController : MonoBehaviour
{
private float speed = 0.0f;
private Animator anim;
GameObject thePlayer;
void Start()
{
thePlayer = GameObject.Find("TractorTest");
anim = thePlayer.GetComponent<Animator>();
}
void Update()
{
Debug.Log("space" + speed);
speed = speed + 0.01f;
anim.speed = speed;
}
}
Your answer
