Instantiating a GameObject from a ScriptableObject
Hi, I am currently working on a system where the main character can summon/instantiate AI from a library, which is held in a scriptableObject. I get a NullRefExeption error.
This is the scriptable object.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class DatabaseOfMinions : ScriptableObject {
public Minions[] minions;
}
//what is in our database
[System.Serializable]
public class Minions
{
public string name;
public GameObject prefab;
public Sprite prefabSprite;
public Rigidbody body;
public int minionIndex;
public int damageBlockingIndex;
public float health;
public float detectionRadius;
public float attackRadius;
public float attackDamage;
public float speed;
public float jumpHeight;
}
This is the script that i use to instantiate:
using UnityEngine;
using System.Collections;
public class MinionsSummoningManagerScript : MonoBehaviour {
public DatabaseOfMinions database;
//public Transform spawnPositionOnLeft;
public Transform spawnPositionOnRight;
public bool canSummon = true;
void Awake()
{
if (!database)
{
database = Resources.Load("MinionDatabase") as DatabaseOfMinions;
}
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown("a"))
{
if (canSummon)
{
GameObject obj = Instantiate(database.minions[1].prefab, spawnPositionOnRight.transform.position, Quaternion.identity) as GameObject;
}
}
}
}
Any help would be much appreciated. Thank you :).
Answer by RX187 · Aug 07, 2018 at 06:50 PM
You may have figured this out by now but I tested your code and it actually works:
On the DatabaseOfMinions script add [CreateAssetMenu(menuName = "New Game")] this will create a menu when your right click in the inspector and you can add the scriptable object. ;
Move the scriptable object to the Resources folder as your path indicates.;
Put the MinionsSummoningManagerScript script on a game object in the scene;
Grab the scriptable object that you placed in the Resources folder and place it on the empy slot in the empty game object you created.
Hit play and it should work.