I keep getting this error:
error( 14,69) CS0120: An object reference is required to access non-static member `UnityEngine.Object.name’
Anyone know whats wrong in my code?
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
public class AudioManager : MonoBehaviour
{
AudioClip clip1 = (AudioClip) Resources.Load("Sound/Sword1");
public void AddToFirstAvailable(AudioClip newAudio)
{
if (gameObject.tag == "Slot1" && Sprite.name == "Sword") <------- ERROR HERE
{
if (gameObject.name =="Button 1")
{
newAudio = clip1;
}
if (gameObject.name =="Button 2")
{
newAudio = clip1;
}
if (gameObject.name =="Button 3")
{
newAudio = clip1;
}
if (gameObject.name =="Button 4")
{
newAudio = clip1;
}
if (gameObject.name =="Button 5")
{
newAudio = clip1;
}
if (gameObject.name =="Button 6")
{
newAudio = clip1;
}
}
}
}
You’re trying to access the name variable of the Sprite class. Without looking it up, I can tell you that the Sprite class probably does not have a static, public variable called name for you to access.
Generally, when you see a capitalized name it’s referring to the class, not an instance of that class. In this case, that instance is what you actually want. I don’t know what sprite you’re trying to compare against, but you should be finding that object and not referring to the Sprite class itself.
Slot1 is a UI Image object and Button1-6 are Child UI Button Objects of Slot1 so I am trying to say if Slot1’s Sprite = Sword then the 6 Buttons AudioClips will be clip1 on buttons 1-6.
(I used clip 1 for all the newAudio = just to test if the script works, ill change to clip1, clip2, clip3 ect later after I add those sound files)
Okay, so I’m not positive on how you have this all set up, but I’m thinking you need to do a gameObject.GetComponentInChildren().texture.name where you currently have Sprite.name. The idea is that you want to get the Sprite component of the object and see what its assigned texture is called, right?
Though looking at it that way, I have to believe there’s a better way to do this, haha.
I currently have this script attached to my UI image called slot1 and the 6 buttons are children objects of slot one. If I am saying if slot 1s Sprite image is a sword then change the audio for all 6 child buttons of slot one will this work? can a sciprt attached to a UI image only change the Audio clip of the Buttons that are children objects of slot1 or do i need to attached the script to the buttons as well? can you reference objects outside of a script?