- Home /
Player GameObject changes position when I start the game
Dear Community, I am another newcomer to Unity3d and C#. I have created a scene in order to grasp the concept of classes and instances. In the scene a player (capsule) stands in front of a bank (lots of cubes) next to his car(another cube). (see here)
As you can see the Player Controller has a "Character Controller" Component attached and a "Client Controller" Script, which goes like this:
using UnityEngine; using System.Collections;
public class ClientController : MonoBehaviour {
public float speed = 4.0f;
public float jumpSpeed = 7.0f;
public float gravity = 30.0f;
Vector3 direction = Vector3.zero;
CharacterController controller;
void Start ()
{
controller = GetComponent<CharacterController> ();
}
void FixedUpdate ()
{
Move ();
}
void Move ()
{
if (controller.isGrounded)
{
direction = new Vector3 (Input.GetAxis ("Horizontal"), 0f, Input.GetAxis ("Vertical"));
direction *= speed;
if (Input.GetButton ("Jump"))
{
direction.y = jumpSpeed;
}
}
direction.y -= gravity * Time.deltaTime;
controller.Move(direction*Time.deltaTime);
}
}
My problem is, that as soon as I switch to Game mode my Player GameObject moves out of the camera view, to a weird position somewhere, where no man has gone before (see here)
I don't know why?? This does not happen if I deactivate the Client Controller Script or my "character Controller" component or both. The error occurred after I altered my "police" prefab, that is instantiated when the player enters the bank not using the door (or metal detector). Can anyone help me? Thank you!
Answer by Capricornum · Sep 12, 2017 at 09:14 PM
Allright. I figured it out. Actually its quite interesting: Before the error occurred I had added my "police" prefab (a yellow capsule) to the scene. Some minutes before I had changed "police's" mesh to a cube in the Mesh Filter component. (I had originally created it as a capsule), and had removed the capsule collider and added a cube collider. This time I changed the mesh back to a capsule and added another capsule collider (removing the cube collider). To make things tidy i moved the collider component up in the inspector (with that gear menu) upon which I received a message, that this action would break my prefab. I continued, because I assumed it wouldn't be so bad. :) And finally I hit -apply- so that my new "police's" settings in the scene would be applied to my prefab. What actually happened is that my GameObject "Floor" (a plane) had suddenly changed its mesh collider component to a capsule collider component. This in turn kicked my Player Object away from it on game start. - Weird - Thank you everyone.
Answer by Litleck · Sep 12, 2017 at 08:27 PM
It might be your if statement triggering at the beginning causing it to move, that's all I can think of.
Answer by bluebird331 · Oct 18, 2020 at 08:47 AM
I'm having trouble with the codes. Please remove this error code! pls