0
votes

Im trying to change the camera position with this script but I am getting the error Assets/Scripts/ChangeView.cs(15,35): error CS0120: An object reference is required to access non-static member `UnityEngine.Transform.position'

I am new to unity and C#.

using UnityEngine;
using System.Collections;

public class ChangeView : MonoBehaviour {

    private bool view;
    private Transform trans;
    void Start () {
        view = true;
        trans = GetComponent<Transform> ();
    }
    public void ChangeCamera () {
        if (view == true) {
            view = false;
            Transform.position = new Vector3 (0.0f, 5f, -5f);
        }
        else {
            view = true;
            Transform.position = new Vector3 (0.0f, 1f, -1f);
        }
    }
}
1
Probably you want to use that variable trans but. of course, you need to initialize it before. - Steve
@Steve it's initialized in Start which is like a constructor in Unity. - D Stanley

1 Answers

0
votes

Do not use the actual class of Transform, use trans. ( I am assuming you are assigning this in the inspector)

So you need

trans.position = Vector3.MoveTowards() or trans.position = new Vector3()

The problem is you are trrying to manipulate Transform as if its a static class, you are not referencing trans in the logic at all.

Edit: Also, if you can assign variables from the inspector, its better to do so than using GetComponent. In your case, since its inheriting from monobehaviour you already have access to transform through the following

gameObject.transform.position

or just

transform position

There is no need to make a private variable for a Transform unless it another objects Transform.