Jump to content

How to pass data between components and AppWorldLogic?


photo

Recommended Posts

Hi ,

I got a problem.

I have created a StructDeclaration.cs under the folder of source of my project. There is a struct like below in that file:

public struct ExternStruct
{
    public int data;
}

I need to fill this struct in AppWorldLogic like this:

public ExternStruct externStruct;

public override bool Init()
{
    externStruct.data = 147;

    return true;
}

Now here it the problem: how can I use the data of the struct in components? I write some code like:

public ExternStruct externStruct;
	
private void Update()
{
     Log.Message("-> The data of extern struct is {0}(Component)\n", externStruct.data);
}

But it doesn't work.

Link to comment

Hi songtao.han,

You need to get a reference to your AppWorldLogic instance.
Use this in your component:

(Engine.GetWorldLogic(0) as AppWorldLogic).externStruct.data

Best regards,
Alexander

Link to comment
21 minutes ago, alexander said:

Hi songtao.han,

You need to get a reference to your AppWorldLogic instance.
Use this in your component:


(Engine.GetWorldLogic(0) as AppWorldLogic).externStruct.data

Best regards,
Alexander

I changed the code to:

	private void Update()
	{
        int data = (Engine.GetWorldLogic(0) as AppWorldLogic).externStruct.data;
        Log.Message("-> The data of extern struct is {0}(Component)\n", data);
		// write here code to be called before updating each render frame
		
	}

But I got this:

image.thumb.png.ba8196875cf64bc67cb02567b8bb437e.png

Link to comment

Or, alternatively, you can use AppWorldLogic as a singleton:

class AppWorldLogic : WorldLogic
{
	// singleton design pattern
	private static AppWorldLogic instance;
	public static AppWorldLogic Get() { return instance; }

	public override bool Init()
	{
		instance = this;
		return true;
	}
}

Then:

Log.Message("-> The data of extern struct is {0}(Component)\n", AppWorldLogic.Get().externStruct.data);

 

Link to comment
13 minutes ago, silent said:

Instead of Engine.GetWorldLogic(0) try to use Engine.GetWorldLogic(1). It looks like internal ComponentSystem Logic is used in this case.

Thanks!

Thanks! It works.

But I need to ask more. 

If I write the code like:

AppWorldLogic.cs

public static StructDeclaration.ExternStruct externStruct;

public override bool Init()
{
    externStruct.data = 0;
    return true;
}

public override bool Update()
{
    externStruct.data += 1;
    return true;
}

Component

private void Update()
{
    Log.Message("-> The data of extern struct is {0}(Component)\n", UnigineApp.AppWorldLogic.externStruct.data);
}

It also works.

I want to know that can the code above cause some unexpected issue?

Link to comment

I want to know that can the code above cause some unexpected issue?
Only if you use more than one AppWorldLogic instance (if you use Engine.AddWorldLogic() method). :-)

Link to comment
×
×
  • Create New...