New

From ZDoom Wiki
Jump to navigation Jump to search

clearscope Object new(class<Object> type)

Usage

A generic object function that can be used in ZScript to create an instance of any object.

Warning: There are some classes that cannot be instantiated with New() and instead have their own methods:

The primary use of this function is to instantiate non-Actor objects, like menus, thinkers and such.

Parameters

  • class<Object> type
The name of the class to create.

Return value

Returns a pointer to the instantiated object.

Examples

Note, it's usually considered good practice to create a dedicated Create() method when there's a need to instantiate a custom class, simply so that instantiation and setup can be performed in a single call. That method has to be defined as static.

This is an example of a Thinker that can be attached to a killed monster to make them fade out gradually:

class CorpseFader : Thinker
{
	Actor victim; //pointer to monster

	// This is the create method, with an argument
	// to pass a pointer to the monster:
	static CorpseFader Create(Actor victim)
	{
		// Create and null-check the thinker:
		let c = New('CorpseFader');
		if (c)
		{
			// Pass the victim pointer to the thinker:
			c.victim = victim;
		}
		// Always return a pointer to the created object:
		return c;
	}

	override void Tick()
	{
		// If the victim no longer exists, destroy this thinker:
		if (!victim)
		{
			Destroy();
			return;
		}
		// If the victim is alive, do nothing:
		if (victim.health > 0)
		{
			return;
		}
		// Otherwise fade it out gradually:
		victim.A_FadeOut(0.02);
	}
}

// Example implementation:
class CorpseHandler : EventHandler
{
	override void WorldThingDied(worldEvent e)
	{
		if (e.thing && e.thing.bIsMonster)
		{
			CorpseFader.Create(e.thing);
		}
	}
}

See also