Problem with static function

I have an issue with my code. I am trying to access some static functions but some things are not working properly in the compiler.

static function OnTriggerEnter (other : Collider) {
 	if (other.gameObject.tag == "ball") {		
		
		Instantiate (explosion, transform.position, transform.rotation);		
		Destroy(other.gameObject);
		Destroy(gameObject);				
		score +=50;
		guiScore.text = "Score: " + score;
		print("hit");
	}
}

I get the following errors:

BCE0020: An instance of type ‘UnityEngine.Component’ is required to access non static member ‘transform’.

BCE0020: An instance of type ‘UnityEngine.Component’ is required to access non static member ‘gameObject’.

Can someone please show me problem?

that is not a static function.

remove the keyword static

it makes no sense in that context.

mark if answered please

If you want to use a function across different scripts, use either SendMessage or GetComponent. I know that for at least static classes, they can’t derive from Monobehaviour, which means all of the nice functions / types that come from Monobehaviour is non-existent.

If you wish to use a static function however, you could use an instance variable.

For example:

public class pseudoCodeClass : Monobehaviours
{
 static var instance : pseudoCodeClass;

function Awake()
{
instance = this;
}
}

(If the syntax is wrong I apologize, I use C#)

From this point on, you can reference the class directly:

pseudoCodeClass.instance.YOURFUNCTIONHERE();

Doing it this way is good and bad; good because you can use all of the functions and variables (Even ones using Monobehaviours!), and bad because it limits the “instance” aspect of the script.

I never use static unless I know that I have only one of the object (such as a main camera or main (only) character).

GetComponent would be a lot better if you have more than 1, such as a generic enemy unit or whatnot. However if this is a GameMaster script, then yes, this would work.

ALSO, because the instance variable makes everything static, you don’t have to do anything special to your functions. You could simply make public functions and call them as static through the variable, as shown above.

Hope this helped a little bit. I’m far from a master but I spent a few too many hours on a similar issue.

-If you need anything clarified just ask… I’ll see what I can do.


Re-reading your question a little bit, it looks like I missed some of it.

Try marking your variables as Static and see if that helps at all.

You can not use non-static variables from a static function as it is not running on a specific object. To use variables with a static function, make the variables static as well.