- Home /
Getting Scriptable object variables from a loop.,
Hello!
I want to make a shop system co-working with scriptable objects. What it should be doing is getting all of the objects that are made with my "Weapons" script.
using UnityEngine;
using System.Collections;
[CreateAssetMenu(fileName = "New Weapon", menuName = "Weapon")]
public class Weapons : ScriptableObject {
[Header("Attributes")]
public new string name;
public Sprite icon;
[Header("Prefabs")]
public GameObject modelPrefab;
//public GameObject partToRotate;
public GameObject bulletPrefab;
//public GameObject firepoint;
[Header("Specifications")]
public int damage;
public int health;
public float range;
public float fireRate;
public float turnspeed;
public int cost;
}
And here is the shop part of it: (For now it should just load the icon.)
using UnityEngine;
using UnityEngine.UI;
public class Shop : MonoBehaviour {
public Weapons weapons;
public GameObject shopTurretItem;
void Start()
{
Object[] weapons = Resources.FindObjectsOfTypeAll(typeof(Weapons));
foreach (Object weapon in weapons)
{
GameObject shopItem = Instantiate(shopTurretItem);
shopItem.transform.SetParent(transform);
Image image = GameObject.Find("ShopTurretItem").GetComponent<Image>();
image.sprite = weapon.icon;
}
}
}
But it doesn't seem to work. I'm 100% sure the problem is within the last line, "weapon.icon", because even Visual Studio is highlighting that section, and Unity can't compile. Any help?
Thanks
Answer by DawidNorasDev · Jun 18, 2018 at 01:54 PM
From what I understand, let's suppose you have 3 weapons. You expect the loop to run 3 times, once for each weapon. you Create a gameobject representing the weapon, an parent it somewhere Then, you search GLOBALLY for a object named "ShopTurretItem" and get Image from him, And assign this image to it.
This means only last image will be displayed. Don't you rather want to have all those created objects have it's own images? Than The image component you are looking for is (probably) in the shopItem
gameObject (Or in children) use shopItem.GetComponent<Image>();
or shopItem.transform.Find("PATH_TO_CHILD").GetComponent<Image>();
You can check PATH_TO_CHILD in the hierarchy.
Oh, I noticed a problem. This could be working, but when I get all of the weapons, it stores it inside an Object array, not a weapons one. Is there any way to convert it or something?
Use the generic form:
Weapons[] weapons = Resources.FindObjectsOfTypeAll<Weapons>();
Your answer
Follow this Question
Related Questions
[C#] How to make this code toggleable 3 Answers
My Animation Loops 3/4 of the way through 3 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Game over funcition isn't being called accurately? 2 Answers