- Home /
acces variables from other script
I'm trying to acces a variable out of an other script, and i did find something that should work, but i don't know how exactly
This is the code: var feather : Transform; var script : TrackItems; script = GetComponent("TrackItems");
function OnTriggerEnter () { Destroy(feather.gameObject); script.feathers (script.feathers -1); }
I think it's clear what i want to happen, i just don't know how to Exactly do this, anyone who can help?
Answer by GesterX · Feb 09, 2011 at 10:36 AM
Create an empty GameObject and call it GameState and attach your TrackItems script to it. Set the tag of the GameState object to "GameController" in the inspector.
Your feather object must have a collider set as a trigger.
Attached this script to the feather:
//get the itemTracking Script var itemTracker;
function Start() { itemTracker = GameObject.FindWithTag("GameController").GetComponent(TrackItems); }
function OnTriggerEnter () { itemTracker.feathers -= 1; //subtract 1 from feathers in TrackItems Destroy(gameObject); }
Tried that, but i now get this error:
NullReferenceException: Object reference not set to an instance of an object DestroyFeatherCollision.OnTriggerEnter () (at Assets/scripts/DestroyFeatherCollision.js:8)
What is this script attached to? If it is attached to the feather then you don't need the feather var (first line) and the destroy should be called as Destroy(gameObject).
I would reccommend putting the script.feathers -= 1; above the destroy function call as well.
Also since you are using the OnTriggerEnter function make sure that one of the colliders attached to the feather has the is Trigger box ticked.
I have edited the original answer and included instructions...
Sadly enough, still not working.. now got this errors:
NullReferenceException: Object reference not set to an instance of an object DestroyFeatherCollision.OnTriggerEnter () (at Assets/scripts/DestroyFeatherCollision.js:8)
Assets/scripts/DestroyFeatherCollision.js(6,9): BCE0005: $$anonymous$$ identifier: 'itemTracker'.
$$anonymous$$y mistake I gave you some dodgey syntax. Add var to the start of itemTracker on the first line. I have edited the original answer to reflect this.
Answer by Raymond 2 · Feb 09, 2011 at 11:36 AM
I got it working in an other way, here's what i have done:
//get the itemTracking Script var itemTracker; itemTracker = GameObject.FindWithTag("GameController").GetComponent(TrackItems);
function OnTriggerEnter () { itemTracker.feathers -= 1; //subtract 1 from feathers in TrackItems Destroy(gameObject); }
Congratulations. Essentially I am doing the same except I am assigning the itemTracker in the Start function which would still work. If you think my answer "answered" your question then mark it with the tick. Thanks.