1
votes

I am currently playing around in Unity trying to make/test a 2D game. I keep getting the following error when I attempt to access CharacterMotor.playerx from inside camerafollow.js:

An instance of type "CharacterMotor" is required to access non static member "playerx"

Here are my two scripts:


camerafollow.js

  #pragma strict

 function Start () {
 transform.position.x =  CharacterMotor.playerx;
 }

CharacterMotor.js

    #pragma strict
    #pragma implicit
    #pragma downcast

    public var playerx : float = transform.position.x;
3
I love the "Not Homework" part :) - Ibrahim Najjar
My teacher actually told me to put that :3 But it actually isnt :) - user2894875

3 Answers

2
votes

You could change playerx to static, but I don't think that's what you want to do (there's probably only one player object, but this would prevent you from ever having multiple CharacterMotors). I think you want/need to retrieve the instance of CharacterMotor that is attached to this gameObject.

#pragma strict

function Start () {
    var charMotor : CharacterMotor = gameObject.GetComponent(CharacterMotor);

    transform.position.x =  charMotor.playerx;
}
0
votes

An instance of type "CharacterMotor" is required to access non static member "playerx"

The above error message describes precisely what is happening. You are just trying to access a variable without first creating an instance of it. Keep in mind that UnityScript != JavaScript.

To fix this issue, simply change

public var playerx : float = transform.position.x;

to

public static var playerx : float = transform.position.x;

Though this fixes your immediate problem I do not recommend continuing down this path. I suggest that you learn other aspects of the language first (such as classes) so that you can better organize and construct your data.

See: http://forum.unity3d.com/threads/34015-Newbie-guide-to-Unity-Javascript-(long)

0
votes

CharacterMotor is the type, there can be multiple instantiations of your type in memory at the same time so when you call the type name you are not referencing any instance in memory.

to get an instance of the type that is connected to you current gameobject try this:

var charactorMotor : CharacterMotor = gameObject.getComponent("CharacterMotor");

Now you have access to that instances properties

transform.position.x =  characterMotor.playerx;