- Home /
C# Access to a variable by another script attached in a gameObject in the scene.
I want to access to a variable of the script "ExampleScript", which is put in a gameObject in the scene, called "player", and using it in the script "AccessVariabileScript".
This is the Player Script where there is the variable MyMoreSpeed:
using UnityEngine;
using System.Collections;
public class ExampleScript : MonoBehaviour {
//SpeedBall
public int myMoreSpeed = 0;
void OnTriggerEnter(Collider other){
if(other.gameObject.name == "MoreSpeed"){
myMoreSpeed++;
}
}
Now, in another Script I want to access to the variable myMoreSpeed and, if this variable is >= 1 do somthing, in that case by touching the screen of an touchscreen and, if the myMoreSpeed is >= 1, the speed change.
I tried to do a c# code by myself. But it was useless.
This is the script:
using UnityEngine;
using System.Collections;
public class AccessVariableScript : MonoBehaviour {
public float speed = 1; //<-- Normal speed
public float speedUP = 2; //<-- If all the conditions are true, speed = speedUP
public float speedA = 1;
void Awake(){
GameObject myPlayer = GameObject.Find("Player"); //<-- I tried to find the gameObject in the scene
SpeedA = myPlayer.GetComponent<ExampleScript>().myMoreSpeed; //<-- ????
}
void Update () {
//Simple movement
transform.Translate(0,-speed,0);
//MoreSpeed. In this part of code I don't undertand why if I don't put "SpeedA >=1" works, but if I put it , doesn't work.
if( SpeedA >= 1 /* I don't know if this is correct */ & Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began){
speed = SpeedUP;
}
}
Unity3d doesn't report any error but the script doesn't work as I want.
Another question I want to ask you is how can I decrease The variable myMoreSpeed by 1 point, when the player touch the screen of an Touchscreen?
Thanks for the attention and if you found any typos I apologize, I'm Italian and I don't speak english very well.
Answer by harko12 · Jul 02, 2012 at 10:45 PM
Well, in your find, you have a capital P on player, is that how the gameobject is? If the Find fails, then there's no way the GetComponent could work either. Make sure that is the right string that you're searching for. You could put a tag on your player then try FindGameObjectWithTag as well.
as for your second question, I think myMoreSpeed-- will reduce the speed by one, the same way myMoreSpeed++ increases it.
Answer by ppddgg · Jul 03, 2012 at 05:49 PM
I tried in another way. I create a "`public GameObject myGameObject`";
In unity I put the GameObject with the script in the "myGameObject".
After do that I call the script with "`myGameObject.GetComponent();`".
Finally works. Thanks!
Your answer
![](https://koobas.hobune.stream/wayback/20220613073605im_/https://answers.unity.com/themes/thub/images/avi.jpg)