-2

seeking help regarding a problem I'm facing while creating a footsteps script for Unity. I pasted this code (in C#) off some manual/guide on how to setup footstep sounds but when I save it and go back to Unity an error occurs, saying something like this:

Assets\Footsteps.cs(5,20): error CS0116: A namespace cannot directly contain members such as fields or methods

Here is the code:

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

public AudioClip[] footstepClips;
public AudioSource audioSource;

public float footstepThreshold;
public float footstepRate;
private float lastFootstepTime;

public CharacterController controller;

void Update ()
{
    if(controller.velocity.magnitude > footstepThreshold)
    {
        if(Time.time - lastFootstepTime > footstepRate)
        {
            lastFootstepTime = Time.time;
            audioSource.PlayOneShot(footstepClips[Random.Range(0, footstepClips.Length)]);
        }
    }
}

Additionally, I think the code that I obtained from the coding degree website was outdated. Also if there were any grammatical mistakes in this thread that's because I made this during night time, sorry if you concluded that as a mistake.

aero
  • 3
  • 1

1 Answers1

0

Your code isn't contained in a class. When you create a C# script in unity it automatically has the class declaration for you to put your code in along with the start and update functions.

You need to add the line public class Footstep : MonoBehaviour { underneath the using statements and above the first variable declaration. Don't forget to add a closing curly brace to the end of the file }

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

    public class Footstep : MonoBehaviour {
    
       public AudioClip[] footstepClips;
       public AudioSource audioSource;
    
       public float footstepThreshold;
       public float footstepRate;
       private float lastFootstepTime;
    
       public CharacterController controller;
    
       void Update ()
       {
           if(controller.velocity.magnitude > footstepThreshold)
           {
               if(Time.time - lastFootstepTime > footstepRate)
               {
                   lastFootstepTime = Time.time;
                   audioSource.PlayOneShot(footstepClips[Random.Range(0, footstepClips.Length)]);
               }
           }
       }
   }
Arianne
  • 507
  • 2
  • 7
  • I strongly suggest you change `PlayerController` to `Footstep` since otherwise OP will directly have the next issue for the component not being found by Unity ;) The script and class name have to match exactly and OP's script is called `Footstep.cs` (see error in question) – derHugo Jan 17 '21 at 09:55
  • Thanks! I updated. I went and looked at the tutorial and that part of the question on here totally slipped my mind. – Arianne Jan 17 '21 at 10:05