- Home /
Unique variables for ScriptableObjects?
ScriptableObjects are very new to me but they seem really good so I've been trying to implement them into my game. I'm currently mainly using them to store information about type of ores such as what ore is it, how much points they give, their sprites, etc to be used for generating these ores around a map. It works perfectly fine but I'm wanting to have sprites randomized so not all of the same ore looks exactly the same. The issue is that I can't just randomize the sprite used and place it back within the ScriptableObject as that sprite will be used among all objects that use that ScriptableObject.
I was wondering if there was any way I could get around this without having to create or store the randomized sprite within a completely different class? So i want to be able to store the randomized sprite within the ScriptableObject but have it be different for each ore that uses it.
Answer by ModLunar · Apr 30, 2020 at 12:11 AM
I know this is kind of vague, but would the following code help?
using UnityEngine;
public class OreData : ScriptableObject {
[SerializeField] private Sprite[] sprites = new Sprite[0];
public Sprite GetRandomSprite() {
int randomIndex = Random.Range(0, sprites.Length);
return sprites[randomIndex];
}
}
This would let you choose an array of multiple Sprites that are possible for your 1 ScriptableObject, and then your other code can publicly get a random sprite from the list using GetRandomSprite()
.
That's sorta what I've got currently but what I'm looking for is to be able to store that randomized sprite in a separate variable that is independent to each object.
Basically the reason I need this is because when the player moves far enough away from these ores, they will despawn and so the sprite is removed from a Tile$$anonymous$$ap that I'm using. I want it so when the player comes back, the exact same sprites that those ores were using will be used ins$$anonymous$$d of being fully random each time the ores are spawned.
Could $$anonymous$$athf.PerlinNoise(float x, float y) be useful so you can evaluate a psuedo-random sprite based on your location?
For example, you can make a function like this that takes in the position of your ore, and outputs a random sprite. This guarantees that an ore at one position always gets the same sprite back from the list.
public Sprite GetRandomSpriteByPosition(Vector3 position) {
float factor = $$anonymous$$athf.Clamp01($$anonymous$$athf.PerlinNoise(position.x, position.y));
int randomIndex = $$anonymous$$athf.Lerp(0, sprites.Length - 1, factor);
return sprites[randomIndex];
}