C#/Unity2D | Can't access public class method - c#

I am currently learning Unity and have a question regarding C#.
I have defined a class like this:
using UnityEngine;
public class ObscuringItemFader : MonoBehaviour
{
private SpriteRenderer spriteRenderer;
private void Awake()
{
spriteRenderer = gameObject.GetComponent<SpriteRenderer>();
}
public void FadeOut()
{
StartCoroutine(FadeOutRoutine());
}
public void FadeIn()
{
StartCoroutine(FadeInRoutine());
}
Creating a instance of it works flawlessly, however when I call a public method like I do here:
using UnityEngine;
public class TriggerObscuringItemFader : MonoBehaviour
{
private void OnTriggerEnter2D(Collider2D other)
{
ObscuringItemFader[] obscuringItemFader = other.gameObject.GetComponentsInChildren<ObscuringItemFader>();
if(obscuringItemFader.Length > 0)
{
for(int i = 0; i < obscuringItemFader.Length; i++)
{
obscuringItemFader[i].FadeOut();
}
}
}
It throws me an error stating: "ObscuringItemFader" does not contain a definition for FadeOut.
Does anyone know what exactly is wrong here? Hopefully not just a silly syntax error that I am unable to locate.
Thank you so much in advance!

I cannot find any error with the logic or syntax of this code (other than technically missing class end brackets).
There is potentially another error in a different script that is causing one of these scripts to be unable to compile correctly.
You can select Build > Build Solution in visual studio and if there are any other compile errors causing changes to these scripts to not be applied.

I solved it!
Thanks to #Kalib Crone who assured me that there are no logic/syntax errors I decided to move from VS Code to VS 2022 and look at that, for some reason the ObscuringItemFader class was empty when I opened it with Visual Studio!
When I reopened it in VS Code, the code shown above was there again, but neither Unity nor VS 2022 seem to see it when I open the file with them.

Related

Why is my Unity script not able to be loaded?

I am making a vr game and I am using UnityXR to do so. I am making a script that will have two attach points for an object (pistol). These points change based on which hand is holding the object.
Here is my code:
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.Interaction.Toolkit;
public class XRGrabIneractableTwoAttach : XRGrabInteractable
{
public Transform leftAttachTransform;
public Transform rightAttachTransform;
protected override void OnSelectEntered(SelectEnterEventArgs args)
{
if(args.interactableObject.transform.CompareTag("Left Hand"))
{
attachTransform = leftAttachTransform;
}
else if(args.interactableObject.transform.CompareTag("Right Hand"))
{
attachTransform = rightAttachTransform;
}
base.OnSelectEntered(args);
}
}
However, when I save my code and go into Unity, it gives me this. "The associated script can not be loaded. Please fix any compile errors and assign a valid script." I have absolutely no idea how to fix this as the code looks fine to me. Can someone please help me with this?

c# script class in unity cannot be found despite no compile errors and names matching

I am attempting to amend a c# sharp script to an empty object but I am constantly given the "script class cannot be found" error, not allowing me to add the script to the object. every fix I have found for this issue includes either there being a compile error which is found in the console (my console is entirely empty) or that the names do not match (which they 100% do).
Here is my code below
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class MenuController : MonoBehaviour
{
[Header("Levels to load")]
public string _newGameLevel;
private string levelToLoad;
[SerializeField] private GameObject noSavedGameDialogue = null;
public void newgameYes()
{
SceneManager.LoadScene(_newGameLevel);
}
public void loadgameYes()
{
if (PlayerPrefs.HasKey("Savedlevel"))
{
levelToLoad = PlayerPrefs.GetString("SavedLevel");
SceneManager.LoadScene(levelToLoad);
}
else
{
noSavedGameDialogue.SetActive(true);
}
}
public void QuitButton()
{
Application.Quit();
}
}
Possible reason: the name of the script is different from the class.
Sometimes unity can (in my experience) fail finding the script if the only difference is lower/upper case. When that happens I think I usually need to delete and add a new script.
Try adding a script with different name.
Also try edit->preferences->externaltools-> regenerate project files

After updating my project, I keep getting Identifier expected and Type expected errors in this script. The Errors are all on Line 29

I updated my project yesterday and I'm not the best at scripting yet, but the upgrade caused me to get an error on line 29 (I added a comment there).
I am getting "Type Expected", and "Identifier Expected" both on the same line. But everywhere I look online it seems to be formatted correctly so I'm not sure.
This is the entire script btw.
using System.Collections;
using System.Runtime.CompilerServices;
using UnityEngine;
public class MusicPlayer : MonoBehaviour
{
public AudioClip[] tracks;
public float volume;
public float nextTrackDelay;
private AudioSource _source;
private Coroutine _nextTrackCoroutine;
private void Awake()
{
}
private void Start()
{
}
private void OnDestroy()
{
}
[IteratorStateMachine(typeof(<NextTrackWait>d__8))] //Errors Are Here
private IEnumerator NextTrackWait()
{
return null;
}
}
From .NET's documentation:
You shouldn't apply the IteratorStateMachine attribute to methods in your code. For methods in Visual Basic that have the Iterator modifier, the compiler will apply the IteratorStateMachine attribute in the IL that it emits.
You should remove that line entirely. My guess is something, somewhere, put decompiled code back into the source, where it shouldn't be. You don't need to add that attribute to your code, the compiler will put it for you where it needs to go.

How do I use inheritance in Unity3d MonoDevelop?

So I began learning Swift, but I discovered that I wanted to use Unity3d because it looked interesting to learn, and for games it looked like the better option than Xcode. This meant that I had to learn a new language, however, so I started learning C#. In my project I have 2 classes.
My first Class is LivesDetract. This class is an edge collider. It catches the falling objects, and decreases the life amount:
public class LivesDetract : MonoBehavior {
public int currentLives; //set to 3 in Unity
private int livesDecrementAmnt = 1;
void OnTriggerEnter2D (Collider2D other) {
currentLives = currentLives - livesDecrementAmnt;
}
}
The second class is named GameController. GameController controls the flow of the game. I originally had LivesDetract as a part of GameController, but for organization purposes, I think it should be in its own class. The problem is that I get the following error when I try to inherit from the class LivesDetract:
Error:
"An object reference is required for the non-static field, method, or property 'LivesDetract.currentLives'"
public class GameController : MonoBehavior {
IEnumeratorSpawn () {
while(LivesDetract.currentLives > 0) { // This line is where the error occurs
//Game Actions Occur
}
}
}
I think I have provided enough information, but if more is needed let me know.
In Swift I was able to set the function as a variable:
var livesDetract = LivesDetract()
I could then use:
while livesDetract.currentLives > 0 {
}
That doesn't seem to work in C# though.
You are trying to access currentLives without instantiating the object. You need find the object in Unity before making use of it.

Access script from another script not working

I am trying to access a function, with a bool parameter, from one script to another and just can't get it to work. I have been looking around to try to understand what i am doing wrong.
Here is the script i am calling:
public class MainScript : MonoBehaviour {
public void ManageBoxCollider2D (bool shouldColliderBeEnabled) {
print (">>>>>>>>>>>>>>>>ManageBoxCollider2D: " + shouldColliderBeEnabled);
}
}
I am trying to call it from this script:
public class Sidebar1_Script : MainScript {
public MainScript mainScript;
void Start () {
mainScript.ManageBoxCollider2D (true);
}
}
There is a lot of other stuff in the scripts as well but this is what matters for this question
In the "Sidebar1_Script" I am trying to access "ManageBoxCollider2D" in "MainScript" but it does not work.
I do get the following message:
Object reference not set to an instance of an object
...which i do understand but can't figure out what i am doing wrong.
I would appreciate some help how to do this.
Thanks
It's because unity doesn't know what script that is. If you see in the inspector you're gonna find that public variable MainScript is still empty, also you can't assign scripts in the inspector (I don't know why though, when you drag it there it won't fit in).
Instead change your Sidebar1_Script like this:
public GameObject obj;
void Start () {
MainScript main = obj.gameObject.GetComponent<MainScript>();
main.ManageBoxCollider2D(true);
}
And then assign the game object of obj in the inspector (drag the game object to the public variable).

Categories