- Home /
How to access a variable in my player class from another class.
I am trying to move my obsicles left across the screen at the speed my player is meant to be moving at. My player has a component called Player.cs with a public float speed, and a method getSpeed() which returns speed.
public class Obsticles : MonoBehaviour {
public GameObject p;
private int pSpeed;
private Vector2 playerVelocity;
void Start()
{
p = GameObject.FindWithTag("Player");
pSpeed = p.GetComponent<getSpeed>();
playerVelocity = new Vector2(pSpeed, 0);
rigidbody2D.velocity = playerVelocity;
}
// Update is called once per frame
void Update () {
rigidbody2D.velocity = playerVelocity;
}
}
I thought that this would run getSpeed() on the player and return the players speed, allowing me to use it as the vector for the obstacles to move. However, it is not work. Am I misunderstanding how getComponent works? I tried it without getComponent too, and that also doesnt work. I can't figure out how to get the speed of the player in another class! any help would be amazing, thank you.
you want:
p.GetComponent<Player>().getSpeed(); //not p.GetCompment<getSpeed>();
PAEvenson is correct, you were trying to assign a script component to an int field.
Your answer
Follow this Question
Related Questions
Moving an object in 3D Space ~ Complexity 1 Answer
How to use tag for all players in the Instantiate. 0 Answers
help loading level after destroying objects 1 Answer
manipulating position.y in unity 2 Answers
Buff Follow 1 Answer