I have a player, and a shoot prefab, The player can only be Facing in 4 directions, cause its 2D, and I have something like this in the player script:
// Facing Direction is: 1 = Up, -1 = Down, 1 = Right, -1 = Left
public float FacingDirectionY;
public float FacingDirectionX;
And I have the shoot prefab script like
public float MoveX;
public float MoveY;
public float MoveSpeed;
// Use this for initialization
void Start ()
{
// Example: I want to set MoveX to -1 if the player is facing Left, and only once
//so the bullet wont curve when player changes direction
//Something like " MoveX = PlayerScript.FaceDirectionX " (Im really new at coding)
}
// Update is called once per frame
void Update ()
{
GetComponent<Rigidbody2D>().velocity = new Vector2(MoveX * MoveSpeed, MoveY * MoveSpeed);
//Then MoveX will be -1, and it will move to the Left, until it gets destroyed.
}
}
But I cant figure it out, can someone help me please?
Help you with what exactly?
Honestly, changing variables from one script to another has been answered several times on these forums. Searching around will show you several ways to do it.
Well, I have been searching for an hour and just find that A script changes B script’s variables, but I wans B script to change its own variables to the same numbers as in A script, but they are not in the same object so I cant use the same code I use to change A script’s variables.
There are lots of ways that have been posted, I know because I have answered some of them. The simple idea is you need a reference to the script. Then you need to get the variable from that script and it’s value.
//Script A
public class FirstScript : MonoBehaviour
{
public int firstValue;
void Start()
{
x = 10;
}
}
//Script B
public class SecondScript : MonoBehaviour
{
public FirstScript firstScript;
public int secondValue;
public void getValue()
{
secondValue = firstScript.firstValue;
}
Second script has a reference to first script. In this case, drag and drop in inspector, but you can also assign it some other way (using GameObject.Find for example).
So, If the Player’s script’s name is “Movement” (Cause it was planned only to contain movement but then It became all behavior script), the player GameObject’s name is “Player”, Should it look like this?
Of course it’s not great for prefabs, this was an example of reference a script in another object and accessing it’s variables, nothing more. That’s why I mentioned GameObject.Find as another method, considering there are many ways of setting this up.
@Branthnann I wasn’t disparaging your response. It just seemed likely from the nature of the question the OP wouldn’t be aware that Prefab connections would break once they instantiated. I’ve seen that mistaken idea from a lot of people posting similiar questions.
I get an error message “The type or namespace name “MovementScript” could not be found. Are you missing a using device or an assembly reference?” what does that mean?