- Home /
Question by
Tojteusz · Apr 12, 2014 at 12:03 PM ·
c#charactercontroller
CharacterController in instance object
Hello.
I have a question. I created object by "Object.Instantiate" in Script asigned to Object1. In that script i added
localPlayer.AddComponent(); localPlayer.AddComponent (); In PlayerController i have:
using UnityEngine; using System.Collections;
public class PlayerController : MonoBehaviour {
public float speed;
private Vector3 position;
CharacterController controller = GetComponent<CharacterController>();
//do inicjalizacji
void Start() {
position = transform.position;
}
//Wywoływane raz co klatke
void Update () {
if(Input.GetMouseButton(0))
{
//Lokalizuje gdzie kliknięto w teren
locatePosition();
}
//Porusz sie do pozycji
moveToPosition ();
}
void locatePosition()
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if(Physics.Raycast(ray, out hit,1000))
{
position = new Vector3(hit.point.x, hit.point.y, hit.point.z);
}
Debug.Log (position);
}
void moveToPosition()
{
//if (Vector3.Distance (transform.position, position) > 1) {
Quaternion newRotation = Quaternion.LookRotation (position - transform.position);
newRotation.x = 0f;
newRotation.z = 0f;
transform.rotation = Quaternion.Slerp (transform.rotation, newRotation, Time.deltaTime * 10);
controller.SimpleMove (transform.forward * speed);
// }
//
}
} I get a error : "error CS0236: A field initializer cannot reference the nonstatic field, method, or property `UnityEngine.Component.GetComponent(System.Type)'" What i can do to repair it?
Sorry for my english.
Comment
Answer by robertbu · Oct 01, 2014 at 04:27 AM
The problem is this line:
CharacterController controller = GetComponent<CharacterController>();
It is outside of any function. The solution is to split it up. At the top of the file put:
CharacterController controller;
....then in Start() put:
controller = GetComponent<CharacterController>();