Error in Unity3d

Asked

Viewed 24 times

-1

How can I fix this error? I found nothing about it on the internet... this is the script

`using Unityengine; using Unityengine.AI;

public class Bluecubebehaviour : Monobehaviour {

private Rigidbody BlueCubeMovement;

private NavMeshAgent FollowPlayer;

public Transform PlayerPosition;

private Renderer Appearance;

private bool ActiveNavMesh;

float Velocity = Random.Range(2.5f, 5.8f);

void Start()
{

    ActiveNavMesh = false;

    tag = "YellowEnemyCube";

    float ScaleOfCube = Random.Range(1.0f, 3.8f);

    BlueCubeMovement = GetComponent<Rigidbody>();

    Appearance = GetComponent<Renderer>();

    FollowPlayer = GetComponent<NavMeshAgent>();

    Appearance.material.color = Color.blue;

    transform.localScale = new Vector3(ScaleOfCube, ScaleOfCube, ScaleOfCube);

    BlueCubeMovement.mass = Random.Range(1.0f, 15.0f);

}

void Update()
{

    if (ActiveNavMesh == true) {

        FollowPlayer.destination = PlayerPosition.position;

        FollowPlayer.velocity = new Vector3(Velocity, Velocity, Velocity);

    }

}

private void OnCollisionEnter()
{
    if (BlueCubeMovement.angularVelocity == new Vector3(0, 0, 0)) {

        ActiveNavMesh = true;

    }

}

private void OnCollisionStay()
{
    if (BlueCubeMovement.angularVelocity == new Vector3(0, 0, 0)) {

        ActiveNavMesh = true;

    }

}

}` this script is in a cube... and it appears the following error inserir a descrição da imagem aqui

1 answer

2

This line is causing error in your code as you are starting an object outside of a function.

float Velocity = Random.Range(2.5f, 5.8f);

The error itself says that you are assigning this variable in the instance variable initiator.

Don’t assign any variables outside of Start (Unity by default asks you to start on it, which is the constructor equivalent), and your code will work.

Solution: Just create a variable outside the functions and initialize it inside Start.

Remember, create a variable and start a variable are different things.

  • Ah, thanks! I already corrected! Then this error happens because there is no method to call the Random function?

  • This error happens because you are starting a variable outside of a method scope and within the class scope. You should only start a variable within methods(functions).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.