#Create Instance

1 messages · Page 1 of 1 (latest)

daring solar
#

I took a look at the unity doc, and it LOOKS like this should work, but Unity isn't having it.

    [ContextMenu("Save Waypoints to Scriptable object")]
    private void SaveWaypoints()
    {
        Path path = ScriptableObject.CreateInstance("Path");
        for(int i = 0; i < waypoints.Count; i++)
        {
            path.waypoints.Add(waypoints[i].position);
        }
    }
meager geyser
#

and the error is or are we just supposed to guess?

daring solar
#

sorry, got sidetracked

#

Cannot implicitly convert type 'UnityEngine.ScriptableObject' to 'Path'. An explicit conversion exists (are you missing a cast?)CS0266

meager geyser
#

so, you are not specifying what type of SO you want to Create

daring solar
#

It's a Path SO.

meager geyser
#

so tell the code that

daring solar
#
using System.Collections.Generic;
using UnityEngine;


[CreateAssetMenu(fileName = "Path", menuName = "StudioDMB/EZLerp/Path", order = 1)]
public class Path : ScriptableObject
{
    public List<Vector3> waypoints;
}

meager geyser
#

Path knows what it is. CreateInstance does not know what Path is unless you tell it

daring solar
#

And how do I tell CreateInstance what a Path is if a class definition is not enough?

meager geyser
#

you have not given CreateInstance a class definition

daring solar
#

Pretend I don't know how to do that.

meager geyser
#

but you do know, you do the same thing with your List declaration

daring solar
#

I have created the SO, defined it's parameters, told ScriptableObject.CreateInstance what class I want it to create an instance of.

#

ScriptableObject ScriptableObject.CreateInstance(string className) (+ 2 overloads) Creates an instance of a scriptable object. is what I get from Visual Studio.

#

and it LOOKS like that is exactly what I have given it.

meager geyser
#

try the other overload and pass in
typeof(Path)

daring solar
#

same result

meager geyser
#

you should also be able to use the Generic
CreateInstance<Path>

daring solar
#

aaah

#

Okay, it accepted the generic. Thank you.

#

It would be even better if Unity's documentation told me that.

meager geyser
#

it does if you scroll down

#

public static T CreateInstance();

daring solar
#

It doesn't say that.

#

nor does it say to specify a type as a generic.

#

It says to pass it as a parameter.

#

aaah

#

This is for a garden variety Scriptable Object

#

It must be a convention thing. I have never seen generics written like this.

#

I have seen something along the lines of public static ScriptableObject CreateInstance<T>();

#

like LinkedList<T>

#

or BinaryTree<T>