Sign in to follow this  

Unity Basic event handling

This topic is 3374 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

After reading through this : Link I decided I should do something similar for the interface elements in my project. So I have come up with this :


#include <iostream>
#include <boost/shared_ptr.hpp>
#include <map>


//
// base gui event class
//
class IGUIBaseEvent
{
public :
	virtual void execute()=0;
};

//gui event class
template<class T>
class GUIEvent:public IGUIBaseEvent
{
public:
	GUIEvent(T& obj,void (T::*funcPtr)())
		: _obj(obj),func(funcPtr)
	{}
	
	virtual void execute(){(_obj.*func)();}
	
protected:
	T& _obj;
	void (T::*func)();
};

//
// base class for all interface items 
//
class GUIElement
{
public:
	GUIElement()
	{
		
	}
	boost::shared_ptr<IGUIBaseEvent> onClick;
	boost::shared_ptr<IGUIBaseEvent> onPressed;
	boost::shared_ptr<IGUIBaseEvent> onOver;
	
	//check input?
	virtual void update()
	{
		//if(clicked && onClick)
		 onClick->execute();

		//if(pressed && onPressed)
		// onClick->execute();

	    //if(over && onOver)
		// onOver->execute();
		
	}

};

//
class Interface
{
public:
	Interface()
	{
		m_EndTurnButton.reset(new GUIElement());
		m_EndTurnButton->onClick.reset(new GUIEvent<Interface>(*this,&Interface::onEndTurnClicked));
	}

	void update()
	{
		m_EndTurnButton->update();

		//iterate over all gui items and update them 
		//std::map<unsigned int,boost::shared_ptr<GUIElement>>::iterator it;
		//for(it = m_GUIElements.begin(); it!= m_GUIElements.end(); ++it){
		//	it->second->update();
		//}
	}
private:
	//called when the end turn button is clicked
	void onEndTurnClicked()
	{
		std::cout<<"end turn clicked event fired!\n";
	}
	
	//end turn button
	boost::shared_ptr<GUIElement> m_EndTurnButton;
	//store all interface items in a std::map later
	//std::map<unsigned int,boost::shared_ptr<GUIElement>> m_GUIElements;
};

int main()
{
	boost::shared_ptr<Interface> inter(new Interface());
	
	inter->update();

	return 0;
}

Eventually all gui elements will be store in a std::map and iterated over to check input and they will call the event handlers accordingly.Button states and cursor position will be sent as parameters to GUIElement::update but i left them out as this is just a test program.I haven't included anything into the actual program.Anyway here comes my questions : 1) On this line : virtual void execute(){(_obj.*func)();} _obj is used to call the pointer to member?So _obj.*func points to Interface::onEndTurnClicked?There is now way to call a pointer to member function without a object instance right? I mean _obj must be used to call func. 2) Would it be a problem to always check if the on* shared_ptrs are valid inside GUIElement::update? I guess not because if there isn't any handler assigned to them then even if the cursor is over the element the event will not be fired. Any other suggestions?

Share this post


Link to post
Share on other sites
Rewritten in boost::bind & boost::function
Neat!


#include <iostream>
#include <map>

#include <boost/shared_ptr.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>


//
// base class for all interface items
//
class GUIElement
{
public:
GUIElement()
{

}

boost::function<void()> onClick;
boost::function<void()> onPressed;
boost::function<void()> onOver;

//check input?
virtual void update()
{
if(onClick)
onClick();

if(onPressed)
onPressed();
if(onOver)
onOver();
}

};

//
class Interface
{
public:
Interface()
{
m_EndTurnButton.reset(new GUIElement());
m_EndTurnButton->onClick = boost::bind(&Interface::onEndTurnClicked,this);

}
void update()
{
m_EndTurnButton->update();

//iterate over all gui items and update them
//std::map<unsigned int,boost::shared_ptr<GUIElement>>::iterator it;
//for(it = m_GUIElements.begin(); it!= m_GUIElements.end(); ++it){
// it->second->update();
//}
}
private:
//called when the end turn button is clicked
void onEndTurnClicked()
{
std::cout<<"end turn clicked event fired!\n";
}

//end turn button
boost::shared_ptr<GUIElement> m_EndTurnButton;
//store all interface items in a std::map later
//std::map<unsigned int,boost::shared_ptr<GUIElement>> m_GUIElements;
};

int main()
{
boost::shared_ptr<Interface> inter(new Interface());

inter->update();

return 0;
}

Share this post


Link to post
Share on other sites
Signals and slots are for broadcasting notifications with minimal coupling. Function and bind are for treating functions like proper objects. You may find yourself using them in similar areas of the code but they do different things.

Share this post


Link to post
Share on other sites

This topic is 3374 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Forum Statistics

    • Total Topics
      628714
    • Total Posts
      2984358
  • Similar Content

    • By AndySv
        Total Music Collection (http://u3d.as/Pxo)   THE COLLECTION CONTAINS:   Mega Game Music Collection   Universal Music Collection   Huge library of high quality music for any project! All at an incredibly low price!   - 2,5GB of high quality audio - 100+ different music tracks - Loop and short versions   Action, fantasy, casual, horror, puzzle, epic, dramatic, romantic, positive, inspiring, motivational and more!
    • By Dafu
      FES Retro Game Framework is now available on the Unity Asset Store for your kind consideration!
      FES was born when I set out to start a retro pixel game project. I was looking around for an engine to try next. I tried a number of things, from GameMaker, to Fantasy Consoles, to MonoGame and Godot and then ended up back at Unity. Unity is just unbeatable in it's cross-platform support, and ease of deployment, but it sure as heck gets in the way of proper retro pixel games!
      So I poured over the Unity pipeline and found the lowest levels I could tie into and bring up a new retro game engine inside of Unity, but with a completely different source-code-only, classic game-loop retro blitting and bleeping API. Months of polishing and tweaking later I ended up with FES.
      Some FES features:
      Pixel perfect rendering RGB and Indexed color mode, with palette swapping support Primitive shape rendering, lines, rectangles, ellipses, pixels Multi-layered tilemaps with TMX file support Offscreen rendering Text rendering, with text alignment, overflow settings, and custom pixel font support Clipping Sound and Music APIs Simplified Input handling Wide pixel support (think Atari 2600) Post processing and transition effects, such as scanlines, screen wipes, screen shake, fade, pixelate and more Deploy to all Unity supported platforms I've put in lots of hours into a very detail documentation, you can flip through it here to get an better glimpse at the features and general overview: http://www.pixeltrollgames.com/fes/docs/index.html
      FES is carefully designed and well optimized (see live stress test demo below). Internally it uses batching, it chunks tilemaps, is careful about memory allocations, and tries to be smart about any heavy operations.
      Please have a quick look at the screenshots and live demos below and let me know what you think! I'd love to hear some opinions, feedback and questions!
      I hope I've tickled your retro feels!



      More images at: https://imgur.com/a/LFMAc
      Live demo feature reel: https://simmer.io/@Dafu/fes
      Live blitting stress test: https://simmer.io/@Dafu/fes-drawstress
      Unity Asset Store: https://www.assetstore.unity3d.com/#!/content/102064

      View full story
    • By Dafu
      FES Retro Game Framework is now available on the Unity Asset Store for your kind consideration!
      FES was born when I set out to start a retro pixel game project. I was looking around for an engine to try next. I tried a number of things, from GameMaker, to Fantasy Consoles, to MonoGame and Godot and then ended up back at Unity. Unity is just unbeatable in it's cross-platform support, and ease of deployment, but it sure as heck gets in the way of proper retro pixel games!
      So I poured over the Unity pipeline and found the lowest levels I could tie into and bring up a new retro game engine inside of Unity, but with a completely different source-code-only, classic game-loop retro blitting and bleeping API. Months of polishing and tweaking later I ended up with FES.
      Some FES features:
      Pixel perfect rendering RGB and Indexed color mode, with palette swapping support Primitive shape rendering, lines, rectangles, ellipses, pixels Multi-layered tilemaps with TMX file support Offscreen rendering Text rendering, with text alignment, overflow settings, and custom pixel font support Clipping Sound and Music APIs Simplified Input handling Wide pixel support (think Atari 2600) Post processing and transition effects, such as scanlines, screen wipes, screen shake, fade, pixelate and more Deploy to all Unity supported platforms I've put in lots of hours into a very detail documentation, you can flip through it here to get an better glimpse at the features and general overview: http://www.pixeltrollgames.com/fes/docs/index.html
      FES is carefully designed and well optimized (see live stress test demo below). Internally it uses batching, it chunks tilemaps, is careful about memory allocations, and tries to be smart about any heavy operations.
      Please have a quick look at the screenshots and live demos below and let me know what you think! I'd love to hear some opinions, feedback and questions!
      I hope I've tickled your retro feels!



      More images at: https://imgur.com/a/LFMAc
      Live demo feature reel: https://simmer.io/@Dafu/fes
      Live blitting stress test: https://simmer.io/@Dafu/fes-drawstress
      Unity Asset Store: https://www.assetstore.unity3d.com/#!/content/102064
    • By Dafu
      Hello all,
      I've been hard at work on a new retro pixel-perfect framework called FES Retro Game Framework. It is now available on the Unity Asset Store for your kind consideration!
      FES was born when I set out to start a retro pixel game project. I was looking around for an engine to try next. I tried a number of things, from GameMaker, to Fantasy Consoles, to MonoGame and Godot and then ended up back at Unity. Unity is just unbeatable in it's cross-platform support, and ease of deployment, but it sure as heck gets in the way of proper retro pixel games!
      So I poured over the Unity pipeline and found the lowest levels I could tie into and bring up a new retro game engine inside of Unity, but with a completely different source-code-only, classic game-loop retro blitting and bleeping API. Months of polishing and tweaking later I ended up with FES.
      Some FES features:
      Pixel perfect rendering RGB and Indexed color mode, with palette swapping support Primitive shape rendering, lines, rectangles, ellipses, pixels Multi-layered tilemaps with TMX file support Offscreen rendering Text rendering, with text alignment, overflow settings, and custom pixel font support Clipping Sound and Music APIs Simplified Input handling Wide pixel support (think Atari 2600) Post processing and transition effects, such as scanlines, screen wipes, screen shake, fade, pixelate and more Deploy to all Unity supported platforms I've put in lots of hours into a very detail documentation, you can flip through it here to get an better glimpse at the features and general overview: http://www.pixeltrollgames.com/fes/docs/index.html
      FES is carefully designed and well optimized (see live stress test demo below). Internally it uses batching, it chunks tilemaps, is careful about memory allocations, and tries to be smart about any heavy operations.
      Please have a quick look at the screenshots and live demos below and let me know what you think! I'd love to hear some opinions, feedback and questions!
      I hope I've tickled your retro feels!



      More images at: https://imgur.com/a/LFMAc
      Live demo feature reel: https://simmer.io/@Dafu/fes
      Live blitting stress test: https://simmer.io/@Dafu/fes-drawstress
      My own game I started working on using FES, a roguelike, very early: https://simmer.io/@Dafu/merl
      Unity Asset Store: https://www.assetstore.unity3d.com/#!/content/102064
       
       
    • By Apollo Cabrera
      Yasss!!! My first Unity3d game is on the App Store and Google Play.
      Download please! About 30 minutes to get through 5 missions.
      Let me know what you guys think.
      Thanks a bunch
       
  • Popular Now