Class inside of a same class?

Hello,

I am trying to understand the following C# script from this tutorial: Invoke - Unity Learn

using UnityEngine;
using System.Collections;

public class InvokeRepeating : MonoBehaviour
{
public GameObject target;

void Start()
{
**InvokeRepeating**("SpawnObject", 2, 1);
}

void SpawnObject()
{
float x = Random.Range(-2.0f, 2.0f);
float z = Random.Range(-2.0f, 2.0f);
Instantiate(target, new Vector3(x, 2, z), Quaternion.identity);
}
}

To my understanding this InvokeRepeating class is being defined here, but why we can use this class already within this class? Did I miss something here? Thank you for the help.

InvokeRepeating is a method. Sadly, they named the class the same thing, making this probably not one of the better examples they have done. They should have named the class something else so as not to confuse new people. Either way, you are not accessing the class With the InvokeRepeating call. You can rename the class to something else and everything will still work.

1 Like

Does that script actually even compile and run? It’s a bit surprising if it works, but if so I guess it means that class names and method names are able to share names just fine. It’s not the class being called as a function.

2 Likes

Yeah, I’ll admit I have never tried doing something like that. And it seemed odd it would be a Unity example script. But, I don’t think it’s the best design because it does create confusion for someone learning.

1 Like

Not the best design? This is pants-on-head stupid. Whoever wrote that code should be forced to debug newbie code from the beginner section for a year!

2 Likes

This. I was sure having a member that with the same name as a class was illegal and would throw an error. They are probably getting away with it because it’s a derived class or some weird nonsense.

It’s still #*^@% stupid design.

1 Like