How do I create objects by name in typescript?

Not favoritedFavorited Favorited 0 favourites
  • 3 posts
From the Asset Store
Hand-painted tiles, objects, animated objects, and background to build a colorful Mayan civilization environment.
  • I'm trying to create an object from a family by it's name:

    const newObject = runtime.objects["name"].createinstance(<parameters>);

    This works, but I wanted to do so using a name stored in a variable:

    let objName = "name";

    const newObject = runtime.objects[objName].createinstance(<parameters>);

    TypeScript won't let me do this because it is afraid "objName" won't be a valid value.

    How should I go about this then?

    Thanks in advance.

    edit:

    this works, but I'm not sure how good of a solution it is:

    let objName = "name";

    const newObject = (runtime.objects as any)[objName].createinstance(<parameters>);

  • The problem here is what is the return type of runtime.objects[str]? For example suppose you have a Sprite and a Text object in your project. Will runtime.objects[str].getFirstInstance() return a Sprite instance (with animation APIs) or a Text instance (with text APIs)? TypeScript doesn't know, even if you persuade it that using str is valid.

    If there is only a small number of possible objects that may be created, it may be better to just use a series of if statements comparing the string and creating the right kind of object. If it could be anything at all, then your approach using any is probably all you can do, as you are telling TypeScript basically anything could happen there.

  • Try Construct 3

    Develop games in your browser. Powerful, performant & highly capable.

    Try Now Construct 3 users don't see these ads
  • Alright, thanks for the clarification Ashley!

Jump to:
Active Users
There are 1 visitors browsing this topic (0 users and 1 guests)