Adding to a list from another class - list

I am trying to add the instance of an object that I click on to a list on my control object. However when I do so it says that the reference is not set to an instance of an object. The code I have to instantiate the list on the control object is:
public List<Transform> selected = new List<Transform>();
And I tried to add to it to that list using this code attached to the unit:
if (!selected)
{
// Set selected state
selected = true;
// Add to Selected List
control.GetComponent<ForwardCommandScript>().selected.Add(this.transform);
// Set material colour brighter
oldColour = gameObject.renderer.material.color;
newColour = oldColour + new Color(0.2f, 0.2f, 0.2f);
gameObject.renderer.material.color = newColour;
}
I have tried with transform as well. Later I will try to remove it by finding a reference id that was set when the unit is instantiated so should I try to add the script instead of the object if I need to find its variables and then delete the game object attached to the script. I have tried with the GameObject, transform and the class. I wanted to use the class so I can easily access the variables. I have posted this on unity answers and forums but no one replied in the week it was up and I don't like reposting the same stuff on the same site.
Cheers, Scobbo

Your error NullReferenceException: Object reference not set to an instance of an object states that something in the associated line is null. Since the error message doesn't state which part is null, you have to split your code up and check which part is failing.
I'm not sure how you split it up, but try it this way:
var script = control.GetComponent<ForwardCommandScript>();
if (script == null) Debug.Log("script not found");
if (script.selected == null) Debug.Log("selected is null");
script.selected.Add(this.transform);
Now you should get one of the two messages in your debug log before the exception raises. Either the script was not found and you have to check if it is correctly assigned to the game object and if control is the correct game object, or selected is null which should not happen if you initialized it like you posted...

Thanks for adding the complete Error Message :)
you need to replace
control.GetComponent<ForwardCommandScript>().selected.Add(this.transform);
with
control.GetComponent<ForwardCommandScript>().selected.Add(transform);
because
this
is a reference to the script and not the GameObject. you could also use gameObject.transform which transform is just an abbreviation for

Related

How to check for existence of object in Roblox with lua?

I am trying to code a gui that is dynamically assigned. I have four teams. I am getting stuck at a certain point. I want to make a function that, when a player joins the game, checks if the other teams have already scored to update their labels. It looks like this:
local function updateAllLabelsLateArrival(redPoints, bluePoints, yellowPoints, greenPoints)
game.Players.LocalPlayer.PlayerGui.ScreenGui.ReallyRedTeam.Points.Text = redPoints
game.Players.LocalPlayer.PlayerGui.ScreenGui.ReallyBlueTeam.Points.Text = bluePoints
game.Players.LocalPlayer.PlayerGui.ScreenGui.NewYellerTeam.Points.Text = yellowPoints
game.Players.LocalPlayer.PlayerGui.ScreenGui.LimeGreenTeam.Points.Text = greenPoints
end
The function is remotely triggered from a server-side script when a player joins. The problem I have is that not all four labels might exist. Suppose a green team player joins in when there is only a red team player already playing. It will come back with the error
ReallyBlueTeam is not a valid member of ScreenGui
I thought wrapping each line in an if statement to check if the label exists, like so:
if game.Players.LocalPlayer.PlayerGui.ScreenGui.ReallyRedTeam then game.Players.LocalPlayer.PlayerGui.ScreenGui.ReallyRedTeam.Points.Text = redPoints end
But this is giving the same error. So my question is, how do I check that a label has been created before updating the points? thanks
Assuming this is a localcsript, you can use WaitForChild() which will yield until the label has been created!
game.Players.LocalPlayer.PlayerGui:WaitForChild("ScreenGui"):WaitForChild("ReallyRedTeam"):WaitForChild("Points").Text = redPoints
More information about WaitForChild here!
Alternatively, if you don't know for definite they will be created, you can use FindFirstChild. This won't yield.
if game.Players.LocalPlayer.PlayerGui.ScreenGui:FindFirstChild("ReallyRedTeam") then
print("it exists")
end
More information about FindFirstChild here!
Hope that helps!
If you want them all on one line each then the best to use would be FindFirstChild() as #jjwood1600 has said. I would also recommend making use of a variable to shorten your GUI paths as you can see below:
local function updateAllLabelsLateArrival(redPoints, bluePoints, yellowPoints, greenPoints)
local userGui = game.Players.LocalPlayer.PlayerGui.ScreenGui
if userGui:FindFirstChild("ReallyRedTeam") then userGui.ReallyRedTeam.Points.Text = redPoints end
if userGui:FindFirstChild("ReallyBlueTeam") then userGui.ReallyBlueTeam.Points.Text = bluePoints end
if userGui:FindFirstChild("NewYellerTeam") then userGui.NewYellerTeam.Points.Text = yellowPoints end
if userGui:FindFirstChild("LimeGreenTeam") then userGui.LimeGreenTeam.Points.Text = greenPoints end
end
In normal Lua you can indeed do the if statements the way you did where you don't use FindFirstChild but Roblox's own version RBX.Lua doesn't.

Error - Cannot access display string yet for new node creation in Omnet

I am trying to create a node at run time in my module in Omnet. I am able to create it with this code and its working fine.
cModule* parentmod = getParentModule();
cModule* grantParentMod = parentmod->getParentModule();
cModule* grantParentMod1 = grantParentMod->getParentModule();
// To check if the module is already created
for (cSubModIterator iter(*grantParentMod1); !iter.end(); iter++)
{
EV << iter()->getFullName()<<endl;
if (iter()->getFullName() == "host_send4")
return;
}
cModuleType *meshnode1 = cModuleType::get("inet.networklayer.manetrouting.PASER.meshnode");
cModule *mod = meshnode1->create("host_send4", grantParentMod1);
cDisplayString& dispstr = getDisplayString();
dispstr.parse("p=1000,535;r=200,green");
mod->finalizeParameters();
mod->buildInside();
mod->scheduleStart(simTime()+2*beaconInterval);
However this module is not generated at desired place in simulation output (the coordinates and the display). I believe the display string created here is not attached to the module and hence I tried to do it by this :-
cDisplayString& dispstr = getDisplayString();
dispstr.parse("p=1000,535;r=200,green");
mod->getDisplayString().set(dispstr);
But with this I encounter following error at run time :- Cannot access display string yet: Parameters not yet set up . I know the problem is in mod->getDisplayString().set(dispstr);
So is there any other way to assign the parameter or am I doing some minor error.
Thanks for this help.
Make sure you are following the module creation procedure as given in the OMNeT++ manual.
If you navigate to the The Detailed Procedure sub-section you will notice a comprehensive list which tells what step should be performed where:
Find the factory object;
Create the module;
Set up its parameters and gate sizes as needed;
Tell the (possibly compound) module to recursively create its internal submodules and connections;
Schedule activation message(s) for the new simple module(s).
Step 3 I believe is the one you are looking for. Little below is given a detailed explanation of what should be done for step 3:
If you want to set up parameter values or gate vector sizes (Step
3.), the code goes between the create() and buildInside() calls:
// create
cModuleType *moduleType = cModuleType::get("foo.nodes.WirelessNode");
cModule *module = moduleType->create("node", this);
// set up parameters and gate sizes before we set up its submodules
module->par("address") = ++lastAddress;
module->finalizeParameters();
module->setGateSize("in", 3);
module->setGateSize("out", 3);
// create internals, and schedule it
module->buildInside();
module->scheduleStart(simTime());
Be aware of the usage of the module->par("<parameter_name>") function.
PS: I was writing my answer, and in meanwhile you answered your own question. This answer can be left there for future reference, if useful.
Well I modified the code as :-
cModuleType *meshnode1 = cModuleType::get("inet.networklayer.manetrouting.PASER.meshnode");
cModule *mod = meshnode1->create("host_send4", grantParentMod1);
mod->finalizeParameters();
std::string displayString = "p=1000,535;r=200,green;i=device/smallrouter";
mod->getDisplayString().parse(displayString.c_str());
mod->buildInside();
mod->scheduleStart(simTime()+2*beaconInterval);
and then its working perfect. According to my understanding, I should add mod->finalizeParameters(); before changing the display setting and display string should be a simple string but not the cDisplayString object.

ColdFusion function variable name and CfBuilder

I need to call a function of an object and pass it a variable. Because I need to make multiple call to function of this object I've tried to make one only handler that invoke the specific function by the form value I pass it. The code works, but CFBuilder show me that there is an error (missing semicolon on the last row). I'm on Railo.
local.myReport = seoUtility.init();
local.func = form.action;
local.report = local.myReport[local.func](form.user);
So the question is: this code is correct? I could simply ignore the cfbuilder error icon?
If you don't want CFBuilder to nag you about the syntax, you can change to this:
local.myReport = seoUtility.init();
local.func = local.myReport[form.action];
local.myReport.func = local.func;
local.report = local.myReport.func(form.user);
This sets local.func to the instance of seoUtility as a reference to the actual function you want to call, preserving its relationship to the parent object. This way the offending []() syntax isn't needed.
However, this only works if seoUtility.init() is returning a fresh instance every time, as opposed to a singleton shared by the application, in which case there would be a race condition on all calls to local.myReport.func().

Accessing values in Flex Object result from Zend AMF originated as PHP associative array

I cannot access values in Flex Object (ArrayCollection) after I receive it from Zend AMF. The original type sent is PHP associative array which is simply returned like
return $this->sections['initial_setup'];
PHP Variable view:
The required result sent looks like this in Charles AMF RPC tab:
But when I receive the data in Flex as Object (or String[] - it doesn't matter), I cannot access the property values in such code
var result:Object = event.result;
if (result['database'] == 'yes' && result['admin'] == 'yes')
// continue branch ...
and I get exception on the if-line:
Error: Unknown Property: 'database'.
at mx.collections::ListCollectionView ...
Finally, I can see in Eclipse variables view that ResultEvent instance carries a result of type ArrayCollection with 0 length and the values received are visible with D icon (I couldn't find what D adornment means):
But why I still can't access them at all and what should I do to use them?
I have tried to change types of Array or ArrayCollection instead of Object. Also there is a thread discussing similar problem, but after trying that out, it doesn't help too.
Any help will be much appreciated :o)
EDIT 1:
Here is the code of FB generated super class constructor for the ConfigurationService:
// Constructor
public function _Super_ConfigurationService()
{
// initialize service control
_serviceControl = new mx.rpc.remoting.RemoteObject();
// initialize RemoteClass alias for all entities returned by functions of this service
var operations:Object = new Object();
var operation:mx.rpc.remoting.Operation;
operation = new mx.rpc.remoting.Operation(null, "readSettings");
operation.resultType = Object;
operations["readSettings"] = operation;
operation = new mx.rpc.remoting.Operation(null, "writeSettings");
operations["writeSettings"] = operation;
operation = new mx.rpc.remoting.Operation(null, "readDBSettings");
operation.resultType = valueObjects.ConnectionParams;
operations["readDBSettings"] = operation;
operation = new mx.rpc.remoting.Operation(null, "writeDBSettings");
operations["writeDBSettings"] = operation;
operation = new mx.rpc.remoting.Operation(null, "readInitSetupCompletion");
operation.resultType = Object;
operations["readInitSetupCompletion"] = operation;
operation = new mx.rpc.remoting.Operation(null, "writeInitSetupCompletion");
operations["writeInitSetupCompletion"] = operation;
_serviceControl.operations = operations;
_serviceControl.convertResultHandler = com.adobe.serializers.utility.TypeUtility.convertResultHandler;
_serviceControl.source = "ConfigurationService";
_serviceControl.endpoint = "gateway.php";
preInitializeService();
model_internal::initialize();
}
So what's happened here is that the Array that's serving as the source for your ArrayCollection is acting as a generic Object with those same two properties. Probably the generated code is assuming you'll always get back more than one object and is having problems when your data doesn't fulfill the assumptions Adobe's engineers made about it. One of the reasons I don't like generated code :-).
Check out these resources on how to "roll your own."
Thoughts on Remoting
AMFPHP to Flex Object Relational Mapping
Implementing PHP Services
I think this last (3) is closest to what you probably have in PHP. If you do decide to go with a VO, you can probably just add an $explicitType to your row return and not need to change too much else on the PHP side. You'll probably need to regenerate your services if you go that route, because I suspect the generated code will be different. The good news is the Adobe engineers probably did think of the case where you have an explicit type, but only one record.
Another fix is to just check your AC for having a source of zero length that is not null and looking for your properties on the edges of that.

Changing the Total Number of Recent Files

I'd like the user to be able to edit the number of recent files shown in the File menu of my MFC application. I've used two very good references:
http://www.codeproject.com/KB/menus/changemru.aspx
http://www.microsoft.com/msj/0899/c/c0899.aspx
It involves deleting and recreating the CRecentFileList object stored in CWinApp::m_pRecentFileList. Unfortunately, I find that the menu is not updated properly after replacing the CRecentFileList. See code snippet below:
void CMyWinApp::SetMRUListSize( int size )
{
// size guaranteed to be between 1 and 16
delete m_pRecentFileList ;
LoadStdProfileSettings( size ) ;
}
What can I do to ensure that what is drawn into the File menu is synchronized with m_pRecentFileList after I recreate the object?
My CApp derives from CWinApp. In initInstance, you have this line:
LoadStdProfileSettings(10);
At the end of InitInstance, add this code:
m_pmf->m_pRecentFileList = m_pRecentFileList;
Here m_pmf is my MainFrame class and I created a member CMainFrame::m_pRecentFileList of type CRecentFileList which is in the MFC source file filelist.cpp. m_pRecentFileList on the right is protected and CMainFrame doesn't have access to it from outside InitInstance, but you can make a functional copy here.
At the end of CMainFrame::OnClose, force a registry update by:
m_pRecentFileList->WriteList();
// Force registry update on exit. This doesn't work without forcing.
I don't even have to rebuild m_pRecentFileList, the MRU mechanism updates it correctly. Example: 5 MRU items, the first is moved to another directory and can no longer be found. Stepping through the code in the debugger shows that the bad entry is removed from the list. For some reason, the updated list isn't saved correctly unless I force it as explained above. I originally thought the problem might have something to do with privileges (64-bit Win7), but running the app as admin didn't help.
Some of Microsoft's documentation suggest you should call CWinApp::LoadStdProfileSettings from within InitInstance. This suggests to me that it's something done once during initialisation rather than at run time.
Have you tried fully implementing the second of the two links you provided? My guess is you need to add the second part instead of the call to CWinApp::LoadStdProfileSettings:
m_pRecentFileList = new CRecentFileList(0, strSection, strEntryFormat, nCount);
if(m_pRecentFileList)
{
bReturn = TRUE;
// Reload list of MRU files from registry
m_pRecentFileList->ReadList();
}
[Edit] Apparently m_pRecentFileList points to an CRecentFileList Class . Have you tried calling CRecentFileList::UpdateMenu?
There's another CodeProject example which might help too.