- Home /
How to use non-MonoBehaviour class in a unity Script
I can't understand why when I use a method of the Colors class in PlayerMovement, the PlayerMovement component is disabled.
The class Colors is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Colors
{
private Color[] color = new Color[3];
public Colors()
{
color[0] = Color.red;
color[1] = Color.blue;
color[3] = Color.green;
}
public Color chooseRandomColor()
{
int index = Random.Range(0, 3);
return color[index];
}
public bool areColorEquals(Color color1, Color color2)
{
if (color1 == color2)
return true;
else
return false;
}
}
The class PlayerMovement is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
Colors playerColor = new Colors();
//componenti
private Rigidbody2D playerRb;
private SpriteRenderer playerSpriteRenderer;
[Header("Movimento")]
[SerializeField] private float horizontalSpeed;
private float horizontalInput;
// Start is called before the first frame update
void Awake()
{
playerRb = gameObject.GetComponent<Rigidbody2D>();
playerSpriteRenderer = gameObject.GetComponent<SpriteRenderer>();
playerSpriteRenderer.color = playerColor.chooseRandomColor();
}
private void Start()
{ }
private void Update()
{
horizontalInput = Input.GetAxisRaw("Horizontal");
}
// Update is called once per frame
void FixedUpdate()
{
playerRb.MovePosition(playerRb.position + Vector2.right
* horizontalInput * horizontalSpeed * Time.fixedDeltaTime);
}
private void OnTriggerEnter2D(Collider2D collision)
{
Debug.Log("Morto");
if (collision.gameObject.tag == "Block")
{
Object.Destroy(gameObject, 0f);
}
}
}
Answer by sleepy_coder · Apr 16, 2021 at 09:26 AM
In Colors class constructor green color assignment is out of array range. So Unity receives an exception when instantiating your component and probably decides that it is unusable.
Answer by shyvert9 · Apr 15, 2021 at 06:24 PM
I solved the problem using static methods, but I still don't understand why the problem should arise
Your answer
Follow this Question
Related Questions
Is it possible for a non-MonoBehaviour class to use built-in functions? 1 Answer
Instantiating a MonoBehavior Class at runtime and pass it a normal Class 1 Answer
How do I use "helper classes" in C# and have them show up in the Inspector? 1 Answer
Can I call a class's method which inherit monobehaviour by a normal class? 0 Answers