Get variable from other GameObject's script

I tried to get the variable nbullet from the script Control of the GameObject Player, I wrote this script:

using UnityEngine;
using System.Collections;

public class Info : MonoBehaviour {

public int nbullet;
public GameObject player;
void Start () {
}
void Update () {
    player = GameObject.Find("Player");
    nbullet = GetComponent("Control").nbullet;
    }
}

but it tells me this error:

Assets/Info.cs(29,52): error CS1061: Type UnityEngine.Component’ does not contain a definition for nbullet’ and no extension method nbullet’ of typeUnityEngine.Component’ could be found (are you missing a using directive or an assembly reference?)

why? how can I fix this?

I've spotted the issue. Everything is correct except for line 12. You wrote nbullet = GetComponent("Control").nbullet. This is almost correct. You forgot to GetComponent from the player, and I think the GetComponent could potentially have incorrect syntax. So it should be more like this: nbullet = player.GetComponent<Control>().nbullet;

3 Answers

3

If the nbullet variable is public you just have to cast the Component to the script like this:

var controlscript : Control = player.GetComponent("Control");
nbullet = controlscript.nbullet; //You should also consider renaming your nbullet variable

what kind of variable is Control? I can't use it.

Nvm you're using C#. Control is the script so the variable type is called Control. In your case it would be: Control controlscript = player.GetComponent<Control>(); If you want to read about how to access variable from other scripts follow this link: http://docs.unity3d.com/Documentation/ScriptReference/index.Accessing_Other_Game_Objects.html

thx,now it run but it stop telling: NullReferenceException UnityEngine.GameObject.GetComponent[Control] () (at C:/BuildAgent/work/6bc5f79e0a4296d6/Runtime/ExportGenerated/Editor/BaseClass.cs:180) Setting.Update () (at Assets/Setting.cs:40) what's a NullReferenceException ?

A NullReferenceException occurs when you reference something in your script which doesn't exist. In this case maybe there is no Control script attached when you're using getComponent.

Thx I found the error, I was searching the GameObject Player but instantiating the Player it was named Player(Clone). Thank you really much

I’ve spotted the issue. Everything is correct except for line 12. You wrote nbullet = GetComponent("Control").nbullet. This is almost correct. You forgot to GetComponent from the player, and I think the GetComponent could potentially have incorrect syntax. So it should be more like this: nbullet = player.GetComponent<Control>().nbullet;

You should learn how to use this site. This has many answers all over the place.

Also look there: unitygems.com - unitygems Resources and Information.
Having scripts interact - Questions & Answers - Unity Discussions