- Home /
getting the transform.position of a public static Transform?
Any help would be grand!
I am trying to recieve the transform.position of a global Transform for a Spawn function.
Here's what I am working with so far...
public class Creature_Movement : MonoBehaviour
{
public static Transform spawnPointForPlayer1;
public static void Spawn()
{
// reset the character's speed
movement.verticalSpeed = 0.0f;
movement.speed = 0.0f;
// reset the character's position to the spawnPoint
transform.position = Creature_Movement.spawnPointForPlayer1.transform.position;
}
}
What is the problem that you're running into? Are you getting a NullPointerException, or some other problem?
There's 3 error messages.
Assets/Scripts/Creature$$anonymous$$ovement.cs(330,17): error CS0120: An object reference is required to access non-static member Creature_$$anonymous$$ovement.movement' Assets/_Scripts/Creature_$$anonymous$$ovement.cs(332,17): error CS0120: An object reference is required to access non-static member
Creature_$$anonymous$$ovement.movement'
Assets/Scripts/Creature$$anonymous$$ovement.cs(338,17): error CS0120: An object reference is required to access non-static member `UnityEngine.Component.transform'
Answer by aldonaletto · Jan 08, 2014 at 02:22 AM
So, what's the problem? Although somewhat weird, this code should work. Static variables don't appear in the Inspector - is this the problem? If so, you must assign the variable at runtime - maybe with a code like this:
void Start(){
// find the empty object named "PlayerSpawnPoint":
spawnPointForPlayer1 = GameObject.Find("PlayerSpawnPoint").transform;
}
But I wouldn't use static functions and variables in this case - you will have trouble if more than one instance of this script exists, since a static variable is shared by all instances.
Thanks aldonaletto!
I tried placing the GameObject.Find in the start function, ad I still seem to get the same error message.
Assets/Scripts/Creature$$anonymous$$ovement.cs(330,17): error CS0120: An object reference is required to access non-static member Creature_$$anonymous$$ovement.movement' Assets/_Scripts/Creature_$$anonymous$$ovement.cs(332,17): error CS0120: An object reference is required to access non-static member
Creature_$$anonymous$$ovement.movement'
Assets/Scripts/Creature$$anonymous$$ovement.cs(338,17): error CS0120: An object reference is required to access non-static member `UnityEngine.Component.transform'
The script is specific to 1 of 3 players, so there will only be running 1 instance of the script at a time.
Thanks for all the help!
The problem is in the movement variable: a static function (Spawn, in this case) can refer only to local or static variables. You could declare movement static to solve the problem, but again I think that this isn't the best approach: the correct way would be to remove the static keyword from Spawn and the other variables.