Search Unity

[Netcode] Spawning Items server side

Discussion in 'NetCode for ECS' started by hardcodednumber, Aug 27, 2020.

  1. hardcodednumber

    hardcodednumber

    Joined:
    May 26, 2014
    Posts:
    88
    I know how to spawn a specific item with the Ghost Collection and use FindGhostType<T>() to retrieve the index of the item, then spawn it.

    I want to know if there is a more generic way to spawn an item on the server, say itemID 2. In this case a gun or a health pot. Then I can programmatically create pickups.

    Maybe something like this where I know the itemID:

    var ghostCollection = GetSingleton<GhostPrefabCollectionComponent>();
    var prefab = EntityManager.GetBuffer<GhostPrefabBuffer>(ghostCollection.serverPrefabs)[itemID].Value;
    var player = EntityManager.Instantiate(prefab);
     
  2. hardcodednumber

    hardcodednumber

    Joined:
    May 26, 2014
    Posts:
    88
    After looking more into the Asteroids demo, it doesn't look possible. I tried creating two actors with two different materials. If you update the ghost list and generate code, it doesn't know how to differentiate the same prefab.

    Is there anyone making a game with, I don't know, multiple characters?
     
  3. TRS6123

    TRS6123

    Joined:
    May 16, 2015
    Posts:
    246
    If each ghost has its own unique component to differentiate from the others, you can use a for loop to search for the ghost with the desired component and then spawn it.
     
  4. Enzi

    Enzi

    Joined:
    Jan 28, 2013
    Posts:
    967
    I use this static extension method:
    Code (CSharp):
    1. public static Entity GetGhostPrefab<T>(this GhostPrefabCollectionComponent ghostCollection, EntityManager entityManager)
    2.     {      
    3.         var prefab = Entity.Null;
    4.         var serverPrefabs = entityManager.GetBuffer<GhostPrefabBuffer>(ghostCollection.serverPrefabs);
    5.         for (int ghostId = 0; ghostId < serverPrefabs.Length; ++ghostId)
    6.         {
    7.             if (entityManager.HasComponent<T>(serverPrefabs[ghostId].Value))
    8.                 prefab = serverPrefabs[ghostId].Value;
    9.         }
    10.  
    11.         return prefab;
    12.     }
    So you only need to know 1 comp that is unique in the ghosts.
     
    florianhanke likes this.