- Home /
Cant Find The Variable In Another Script?
Hi :)
Rookie question, but I am trying to get the "speed" variable from a script called "CheckSpeed" in the "Player" game object. I have checked every spelling and it insists on saying: "'speed' is not a member of 'UnityEngine.Component'"
What am I doing wrong?
My Script So Far:
var bullet : Rigidbody;
var bulletSpeed = 100;
var shipSpeed : float;
function Update () {
shipSpeed = transform.Find("Player").GetComponent("CheckSpeed").speed; // ???
if (Input.GetMouseButtonDown(0))
{
FireGun();
}
}
function FireGun()
{
var clone = Instantiate(bullet, transform.position, transform.rotation);
audio.Play();
clone.velocity = transform.TransformDirection(Vector3(0, 0, bulletSpeed + shipSpeed));
Destroy (clone.gameObject, 3);
}
This should be a very simple solution, but it has stumped me for a good hour. I have never got the hang of referencing variables from other scripts/gameobjects. I wish I could just say stuff like "script.parent.parent.Part" :P
Also I'd like to add, I know this question has been asked a lot and there is a good page by Unity explaining a solution. But despite reading and following them, it doesn't seem to help.
Thanks :)
Answer by robertbu · Jul 11, 2013 at 10:38 PM
Take out the quotes around CheckSpeed:
shipSpeed = transform.Find("Player").GetComponent(CheckSpeed).speed;
When you call GetComponent() with a string, it does not know the type to return, so it returns a reference to 'Component.' But 'Component' does not have a 'speed' variable. If for some reason you want to use the string form of GetComponent(), then you must cast the return value.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Calling a C# function from a Javascript 3 Answers
Space Invaders movement? 1 Answer
Cursor Lock to Center of screen script doesnt work please help. 2 Answers
Application.CommitSuicide? 3 Answers