Click here to Skip to main content
15,881,709 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
this is the console error from unity

[11:27:31] Assets\WanderingAI.cs(44.17) Error CS0116: a namespace cannot directly contain members such as fields or methods

The code i use is here
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WanderingAI : MonoBehaviour {

public float moveSpeed = 3f;
public float rotSpeed = 100f;

private bool Iswandering = false;
private bool Isrotatingleft = false;
private bool Isrotatingright = false;
private bool Iswalking = false;

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

    // Update is called once per frame
    void Update()
    {
        if(Iswandering == false)
        {
            StartCoroutine(Wander());
        }
        if(Isrotatingright == true);
        {
            transform.Rotate(transform.up * Time.deltaTime * moveSpeed);
        }
        if(Isrotatingleft  == true);
        {
            transform.Rotate(transform.up * Time.deltaTime * -moveSpeed);
        }
    }




    }


    IEnumerator Wander()
    {
        int rotTime = Random.Range(1, 3);
        int rotateWait = Random.Range(1,4);
        int rotateLorR = Random.Range(1,2);
        int walkWait = Random.Range(1,4);
        int walkTime = Random.Range(2,5);

        Iswandering = true;

        yield return new WaitForSeconds(walkWait);
        Iswalking = true;
        yield return new WaitForSeconds(walkTime);
        Iswalking = false;
        yield return new WaitForSeconds(rotateWait);
        if(rotateLorR == 1)
        {
            Isrotatingright = true;
            yield return new WaitForSeconds(rotTime);
            Isrotatingright = false;
        }
        if(rotateLorR == 2)
        {
            Isrotatingright = true;
            yield return new WaitForSeconds(rotTime);
            Isrotatingleft = false;
        }
        Iswandering = false;
    }


What I have tried:

i tried checking the code multiple times and checing tutorials but i still cant find the problem.
Posted
Updated 18-Feb-21 17:03pm
Comments
Richard Deeming 19-Feb-21 10:56am    
If you indent your code properly, the problem will become obvious.

* In Visual Studio, press Ctrl+K, then Ctrl+D to format the current document.

* In VS Code, use Ctrl+Shift+I.

1 solution

The lone '}' after the Update() function closes the class definition, therefore Wander() is a method defined directly within the namespace, hence the error. Move that '}' to the very end of the code you posted and that error should go away.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900