Reputation: 11
I have trying to create this code so that my player in Unity walks through a trigger box and sets off specific audio but when I put in this code it comes up with saying there's an Enclosing Error:
[10:51:37] Assets/DoorFall.cs(7,24): error CS0542: 'DoorFall': member names cannot be the same as their enclosing type
I have tried changing different names and moved different nodes around but nothing is working.
public class DoorFall : MonoBehaviour {
public AudioSource DoorFall;
// Use this for initializatoin
void Start() {
DoorFall = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update() {
}
void OnCollisionEnter (Collision collision) {
if (collision.gameObject.tag == "player")
{
DoorFall.play();
Destroy(collision.gameObject);
}
}
}
Upvotes: 1
Views: 929
Reputation: 62213
In your case Compiler error CS0542 is being caused because the type name DoorFall
is the same as the name of one of it's members (the public field). You should rename either the member or the type.
This generates a compile time error because the names conflict. Inside a method body in your type if you write or DoorFall.[memberHere]
the compiler does not know whether to resolve the type or the member. Here is a more succinct example illustrating why this should generate a compile time error.
public class DoorFall {
private static string ToString() { return "A"; }
public AudioSource DoorFall = "B";
void Start() {
// what value would be assigned here?
var result = DoorFall.ToString();
}
}
On a side note it is almost never acceptable to declare a public field. Instead you should use properties to expose field values or to set them. If you want the value to be set/get publicly you could use an auto getter/setter.
public AudioSource DoorFall { get; set; }
If it never accessed from outside the type then declare it as private
instead.
Upvotes: 0
Reputation: 136084
Your class name DoorFall
is the same as a member of the class public AudioSource DoorFall
; name one differently.
Chances are you dont need the member to be public
either.
public class DoorFall : MonoBehaviour {
private AudioSource doorFallAudioSource;
// Use this for initializatoin
void Start() {
doorFallAudioSource = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update() {
}
void OnCollisionEnter (Collision collision) {
if (collision.gameObject.tag == "player")
{
doorFallAudioSource.play();
Destroy(collision.gameObject);
}
}
}
Upvotes: 2