Domanda

I've been searching for this for few hours now and didn't get any result. I have a script called GameSetup.js that is attached to an empty game object (named GM) . It holds references to my current camera and has functions to get screen width and other stuff. I'd like to access these functions ( and variables) from other scripts. so for example I have another empty game object called "Blocks", one of its components is BlockGenerator.js , which has BlockGenerator() function. I want to be able to use screenWidth() in BlockGenerator() like this:

BlockGenerator.js

BlockGenerator(){
var Blocknumber : int =  GameSetup.ScreenWidth / blockWidth;
}

GameSetup.js

   function  ScreenWidth() : float{
        var screenWidth : float = (mainCam.ScreenToWorldPoint(new Vector3(Screen.width,0f, 0f)).x)* 2;
        return screenWidth;

of course GameSetup is not recognized in BlockGenerator.js if I use GetComponent(), for example. I'm not sure if I can drag GM game object in the inspector and pass it to BlockGenerator.js , I haven't tried. but the thing is, it makes the game script very complicated for no good reason. how can I setup and access global functions and variables?

È stato utile?

Soluzione

In the class that holds the BlockGenerator method you need to define a public variable of type GameSetup. Then in the inspector drag the object whose instance variables you wish to access. After that you can access the object in your BlockGenerator method and call its methods and access its instance variables.

Another way is to find the object by tag in BlockGenerator via https://docs.unity3d.com/Documentation/ScriptReference/GameObject.FindGameObjectsWithTag.html or search by type with http://docs.unity3d.com/Documentation/ScriptReference/Object.FindObjectOfType.html.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top