- Home /
Can't import a variable from another script!!
Hi guys, look at this codes please, and if you can, tell me how to solve this problem.
FIRST SCRIPT
using UnityEngine;
using System.Collections;
using System.Timers;
public class WeaponScript : MonoBehaviour
{
public int healthplayer, damagecube=9,ammoa=7, ammob=35, ammoai=7, ammoc=0,ammobi=35;
//other useless code, i think
}
SECOND DIFFERENT SCRIPT
using UnityEngine;
using System.Collections;
public class Ammo : MonoBehaviour
{
public int a;
public WeaponScript ammof;
void Start()
{
ammof = GameObject.FindWithTag("Player").GetComponent();
a=ammof.damagecube;
}
I can't use any variable!! When I run my scene, the Unity's console says:"NullReferenceException: Object reference not set to an instance of an object".
Any ideas?
Answer by Adam-Buckner · Feb 04, 2013 at 11:28 PM
The "Get Component" part does not specify what "Component" you want to get.
This:
ammof = GameObject.FindWithTag("Player").GetComponent();
... should specify what Component Type you are looking for:
ammof = GameObject.FindWithTag("Player").GetComponent("MyComponent");
This will give you a component reference for "ammof". Once you have a valid reference for "ammof", you should be fine.
It might be good, however, to put in some protective layers in your code, just in case you can't find what you're looking for:
void Start()
{
GameObject playerObject = GameObject.FindWithTag("Player");
if (playerObject != null)
{
// The following line uses the "generic" GetComponent
ammof = playerObject.GetComponent <MyComponent> ();
}
if (ammof != null)
{
a=ammof.damagecube;
}
else
{
Debug.Log ("Cannot find 'MyComponent' script");
}
}
This way, if you do fail on any one of these steps, you don't get a nullref! error when running, but a reliable warning about what could be wrong.
Thank you for your help, i found my error! The "WeaponScript" was assigned to a player child, and this player child was not tagged "player"! Thank you very much :)