Script Disappearing on Play

Hey All -

New to Unity and the group. Just finished part 2 of a YouTube tutorial on 2d RPG and have already hit an issue. I associated a script with the player by selecting the character in the Hierarchy window, then dragging the script to the “Add Component” section of the Inspector window. I change the MoveSpeed to 2 (or 5), select the Game tab, hit play, and it builds. Then the script disappears from the Inspector window and the character doesn’t move. Of course, in the tutorial video, everything worked perfectly.

Can anyone tell me what I’m missing? I deleted the script and followed the tutorial again, with the same result. Any help appreciated - and if you need more detail, please ask.

Thanks -

CODE

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{

    public float moveSpeed;
    private bool isMoving;
    private Vector2 input;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    private void Update()
    {
        if(!isMoving)
        {
            input.x = Input.GetAxisRaw("Horizontal");
            input.y = Input.GetAxisRaw("Vertical");

            if(input != Vector2.zero)
            {
                var targetPos = transform.position;
                targetPos.x += input.x;
                targetPos.y += input.y;

                StartCoroutine(Move(targetPos));
            }
        }
    }

    IEnumerator Move(Vector3 targetPos)
    {
        isMoving = true;

        while((targetPos - transform.position).sqrMagnitude > Mathf.Epsilon)
        {
            transform.position = Vector3.MoveTowards(transform.position, targetPos, moveSpeed * Time.deltaTime);
            yield return null;
        }

        transform.position = targetPos;

        isMoving = false;
    }
}

Do you get any errors in the console? Are you adding this script to an instance of a prefab, or just a normal game object? I tried copy/pasting your code into a new project and it worked fine, so the code itself is probably ok.

Add: "void OnDisable(){ Debug.Log("disabled");}" to your PlayerController. Then look at the console after the issue happens. If you click on the message in console, the stack trace will tell you what/where is causing the script to disappear.