i’ve started to learn Unity and we were always using MonoBehaviour Parent and Child Classes. After that i realized that we need to use OOP with our projects. I know how can i create classes and objects in C# and i know essential functions for Unity. How can i learn combining both of them in order to create more advanced programes.
In other words, i don’t get how we can create some Game Objects which are not applied to Monobehaviour class, and instantiate them to the scene. Do i need other Scripts which are related with Monobehaviour class for that?
If you can help me providing some guideline to learn OOP in Unity, i’ld really appretiate for that
:/ I might have explained my problem a little bit bad but this is where i actually have issues.
For Example, with following code i created Item Class and Inventory Class, lets say I’m going to add Sprites to my “Item” how can i handle with that in Unity? Wıth MonoBehaviours i can attach Script to the game objects and take sprite from the editor.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Item {
public enum ItemType {
None,
Sword,
HealthPotion,
ManaPotion,
PowerUpPotion
}
public ItemType itemType;
public float amount;
}
// *******************************************************
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Inventory
{
public List<Item> ItemList;
public Inventory() {
ItemList = new List<Item>();
AddItem(new Item {itemType = Item.ItemType.Sword, amount = 1});
Debug.Log(ItemList.Count);
}
public void AddItem(Item item) {
ItemList.Add(item);
}
}
Melih Altuğ Çelik is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1
For data assets that aren’t necessarily code, but needs to be able to modify within the editor or store Unity objects (like Sprite
), Unity has ScriptableObject
s.
You can create a class that inherits from ScriptableObject
:
public class Item : ScriptableObject {
public enum ItemType {
None,
Sword,
HealthPotion,
ManaPotion,
PowerUpPotion
}
public ItemType itemType;
public float amount;
public Sprite inventorySprite;
}
then you can Right Click (in Assets window) > Create > ScriptableObjects > [Classname] inside your assets folder, and edit or refer to them like any other Unity object.
5