Jump to content

[SOLVED] Check interface on class


photo

Recommended Posts

Hi Honya. To check class interface you can use "is_base_class" function. See the sample:

#include <core/unigine.h>

/**
 * interface
 */
class MyInterface {
	
	virtual void update() {
		
	}
};

/**
 * base class
 */
class Foo {
	
};

/**
 * class extends Foo and has MyInterface interface
 */
class Bar : Foo, MyInterface {
	
	/*
	 * overwrite virtual "update" function of MyInterface interface.
	 */
	void update() {
		log.message(__FUNC__ + ": called\n");
	}
};

int init() {
	
	// create instance
	int instance = new Bar();
	
	// check instance on has MyInterface interface
	// the Bar class extend Foo class, but has a MyInterface interface.
	if(is_base_class(classid(MyInterface),instance)) {
		Bar(instance).update();
	}
	
	return 1;
}

"is_base_class" function correctly works in last SDK.

Link to comment

Thanks for example.

 

I use function is_base_class("IUseable", instance) that return false,  is_base_class(classid(IUseable), interface) return true, so I use it in this format.

 

I found another problem with object cast:

#include <core/unigine.h>

/*
 */
int init() {
	Player player = new PlayerSpectator();
	player.setDirection(Vec3(0.755f,-1.0f,0.25f));
	engine.game.setPlayer(player);

	Container c = new Container();
	Chest ch = new Chest();

	if(is_base_class(classid(IUsable),c)) {
		log.message(IUsable(c).targetText());
	} else {
		log.message("no c");
	}
	if(is_base_class(classid(IUsable),ch)) {
		log.message(IUsable(ch).targetText());
	} else {
		log.message("no ch");
	}


	return 1;
}

/*
 */
int shutdown() {
	return 1;
}

/*
 */
int update() {
	return 1;
}


class IUsable {

	virtual float usableDistance() = 0;

	virtual float visibleDistance() = 0;

	virtual string targetText() = 0;
};

class Item {

};

class Container : Item, IUsable {
	string targetText() {
		return "Container";
	}
};

class Chest : Container {

	string targetText() {
		return "Chest";
	}
};

It crash on line log.message(IUsable(ch).targetText());

with error:

20:02:34 Loading "test/test.world" 3ms
20:02:34 Container
20:02:34 Machine::do_callucfv(): "Chest 000000000BCCAE00 (196608:0:0)" is not a suitable user class
20:02:34 World::loadWorld(): world init function return 0 in "test/test.cpp" file
20:02:34 PropertyManager::clear(): can't find "asset_library/items/items.prop" properties library
20:02:34 PropertyManager::clear(): can't find "Properties/surfaces.prop" properties library
20:02:34 PropertyManager::clear(): can't find "Properties/characters.prop" properties library

This problem fix add interface on Chest class:

class Chest : Container, IUsable {

	string targetText() {
		return "Chest";
	}
};

Thanks

 

Honya

Link to comment

Hi Hanya. This crash seems like a bug. Manually specify the interface solves this problem, but it is a wrong in terms of the OOP.

I think we will fix that in the near future.
Link to comment
  • 2 months later...
×
×
  • Create New...