Hi all,
I’m a beginner coder trying to work through an issue with changing a value of an array that contains ScriptableObjects:
public void AddNewLevel(ScriptableObject newLevel)
{
var index = Array.IndexOf(abilities, "SH_L1");
abilities[index] = (ScriptableObject)newLevel;
}
The issue is with the line: abilities[index] = (ScriptableObject)newLevel;
That’s creating an explicit conversion error. I thought that the (ScriptableObject) would let Unity know what the variable is, but I’m wrong.
Any suggestions?
‘newLevel’ is already typed as a ScriptableObject, you shouldn’t have to cast it with (ScriptableObject)newLevel.
What is the exception you’re getting?
What type is the abilities array?
I have a feeling the exception is actually to do with a type mismatch between the abilities array and ScriptableObject. Especially considering that you have this line:
var index = Array.IndexOf(abilities, "SH_L1");
Which implies ‘abilities’ is a string[ ] array.
What is abilities an array of? If it was scriptablesobjects then it would be a redundant cast,
This is what I’m using to define abilities:
[SerializeField] AbilityConfig[] abilities;
This is my code for creating the array:
void AttachInitialAbilities()
{
for (int abilityIndex = 0; abilityIndex < abilities.Length; abilityIndex++)
{
abilities[abilityIndex].AttachAbilityTo(gameObject);
}
}
And this is the error:
error CS0266: Cannot implicitly convert type UnityEngine.ScriptableObject' to
RPG.Characters.AbilityConfig’. An explicit conversion exists (are you missing a cast?)
Yes, your array is of type AbilityConfig, your newLevel is of type ‘ScriptableObject’.
Just like the exception says, it cannot implicitly convert one to the other.
Does ‘AbilityConfig’ inherit from ‘ScriptableObject’ or something? Why is your AddNewLevel taking in a ScriptableObject as a parameter if you expect to stick it in an array of ‘AbilityConfig’?
“SH_L1” is a scriptableObject within the array
yes, AbilityConfig inherits from ScriptableObject. The array has three ScriptableObjects in it.
It will not find and object in array by it’s name automagically. You need to iterate through the array and check every object if it’s name is “SH_L1” or whatever you’re looking for until it’s found or array ended.
Ok, I’ll have to look up how to do that. Or, would it be better to find it based on it’s order in the array? Like this:
abilities[2] = newLevel;
The particular ScriptableObject is always in that position in the array.