1

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;
2
  • 2
    I love the "Not Homework" part :) Commented Oct 18, 2013 at 13:24
  • 3
    My teacher actually told me to put that :3 But it actually isnt :) Commented Oct 18, 2013 at 13:25

3 Answers 3

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.