Search Unity

  1. Unity Asset Manager is now available in public beta. Try it out now and join the conversation here in the forums.
    Dismiss Notice
  2. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  3. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

IndexOf issue

Discussion in 'Project Tiny' started by NicoSch, Jan 16, 2019.

  1. NicoSch

    NicoSch

    Joined:
    May 14, 2014
    Posts:
    7
    Code (JavaScript):
    1. let gridIndex = grid.Tiles.indexOf(entity);
    2. if (gridIndex == -1) {
    3.  grid.Tiles.push(entity);
    4. }
    indexOf seems to always return -1 even after I push an entity into the array and then try to get the indexOf the exact same entity. Am I doing something wrong?
     
  2. Nkon

    Nkon

    Unity Technologies

    Joined:
    Jun 12, 2017
    Posts:
    65
    Hi there,

    I tried to reproduce with this code but for me it worked as expected:
    Code (JavaScript):
    1. let entity = ut.EntityGroup.instantiate(this.world, "game.TestGroup")[0];
    2. let array = new Array();
    3. let gridIndex = array.indexOf(entity);
    4. console.log("GridIndex: " + gridIndex);
    5. if (gridIndex == -1) {
    6.     console.log("Pushing to array");
    7.     array.push(entity);
    8. }      
    9. gridIndex = array.indexOf(entity);
    10. console.log("GridIndex: " + gridIndex);
    The output log was:
    GridIndex: -1
    Pushing to array
    GridIndex: 0

    Can you post a bit more details about the logic so we can figure this out?

    Cheers!
     
  3. NicoSch

    NicoSch

    Joined:
    May 14, 2014
    Posts:
    7
    This works:
    Code (JavaScript):
    1. for (let cell of grid.Tiles) { //where grid.Tiles is an entity array already populated on a entity component
    2. let cellIndex = grid.Tiles.indexOf(cell);
    3. console.log(cellIndex); //outputs correct index
    4. }
    this does not:
    Code (JavaScript):
    1. for (let cell of grid.Tiles) { //where grid.Tiles is an entity array already populated on a entity component
    2. CheckCell(cell);
    3. }
    4.  
    5. static CheckCell (cell:utEntity) {
    6. let cellIndex = grid.Tiles.indexOf(cell);
    7. console.log(cellIndex); //outputs incorrect index
    8. }
    none of that is real code, but it gets the idea across. I eventually had to send the index to my method instead of the entity to get it working like I want.