I have only a basic C# course finished. And I study the in-build tutorial.
I have kind of count of collectibles and I need to play special effect on the last collectible when the count reaches zero.
So now I need to access variables from a one class to another… And there are couple ways which I can do it in C#
-
Make a class static, so I can access directly these variables.
-
I can instantiate a dynamic class with desired variable, but the problem I need to play visual effect on a collectible, but all logic of count stuff is in UI object…
-
Maybe I can use generic
GetComponent<T>()
method somehow?
I just get frustrated by Unity codding for now, it looks to me pretty chaotic, a lot of things, hard to understand them all, and to find some solution for the problem… Thank you for the answers.
And this is the class for UI object with collectible count proposed for me in the Tutorial.
using UnityEngine;
using TMPro;
using System; // Required for Type handling
public class UpdateCollectibleCount : MonoBehaviour
{
private TextMeshProUGUI collectibleText; // Reference to the TextMeshProUGUI component
public int totalCollectibles;
void Start()
{
collectibleText = GetComponent<TextMeshProUGUI>();
if (collectibleText == null)
{
Debug.LogError("UpdateCollectibleCount script requires a TextMeshProUGUI component on the same GameObject.");
return;
}
UpdateCollectibleDisplay(); // Initial update on start
}
void Update()
{
UpdateCollectibleDisplay();
}
private void UpdateCollectibleDisplay()
{
totalCollectibles = 0;
// Check and count objects of type Collectible
Type collectibleType = Type.GetType("Collectible");
if (collectibleType != null)
{
totalCollectibles += UnityEngine.Object.FindObjectsByType(collectibleType, FindObjectsSortMode.None).Length;
}
// Optionally, check and count objects of type Collectible2D as well if needed
Type collectible2DType = Type.GetType("Collectible2D");
if (collectible2DType != null)
{
totalCollectibles += UnityEngine.Object.FindObjectsByType(collectible2DType, FindObjectsSortMode.None).Length;
}
// Update the collectible count display
collectibleText.text = $"Collectibles remaining: {totalCollectibles}";
}
}
P. S. I edited the proposed script so made the count variable public.