Search code examples
c#stringrandominstantiationvoid

My compiler tells me it cannot convert 'void' to 'string' I understand what this means, but not how to fix it


Here I am trying to instantiate the defined GameObject at random positions (defined in RandomPosOne())

But my compiler says

cannot convert from 'void' to 'string'

public class Enemyspawner : MonoBehaviour
{
    public GameObject Elf;
 
    private void OnCollisionEnter2D(Collision2D collider)
    {
        if (collider.gameObject.CompareTag("SpawnTrigger1"))
        {
            InvokeRepeating((SpawnElfOne()), 2f, 3f);

        }
        void SpawnElfOne()
        {
            Instantiate(Elf, RandomPosOne(), Quaternion.identity);
        }
        
    }

    Vector2 RandomPosOne()
    {
        float x, y;
        x = Random.Range(-8.6f, 8.7f);
        y = Random.Range(3.05f, -3.36f);
        return new Vector2(x, y);
    }

    Vector2 RandomPosTwo()
    {
        float x, y;
        x = Random.Range(-8.8f, 8.8f);
        y = Random.Range(19f, 12.6f);
        return new Vector2(x, y);
    }

}

Solution

  • Move the local void method SpawnElfOne out into the instance

    and pass the target method name as a string parameter when invoking InvokeRepeating

    public class Enemyspawner : MonoBehaviour {
        public GameObject Elf;
     
        private void OnCollisionEnter2D(Collision2D collider) {
            if (collider.gameObject.CompareTag("SpawnTrigger1")) {
                InvokeRepeating("SpawnElfOne", 2f, 3f);
            }           
        }
    
        void SpawnElfOne() {
            Instantiate(Elf, RandomPosOne(), Quaternion.identity);
        }
            
        Vector2 RandomPosOne() {
            float x, y;
            x = Random.Range(-8.6f, 8.7f);
            y = Random.Range(3.05f, -3.36f);
            return new Vector2(x, y);
        }
    
        Vector2 RandomPosTwo() {
            float x, y;
            x = Random.Range(-8.8f, 8.8f);
            y = Random.Range(19f, 12.6f);
            return new Vector2(x, y);
        }
    
    }