Skip to main content
Inspiring
April 20, 2022
Answered

Fetching object from name

  • April 20, 2022
  • 1 reply
  • 148 views

so my goal is to fetch my object from just a string, I want something like this 

	var gems:int = 1;
	
	for(var i = 1; i <= gems; i++) {
		var name:String = "gem"+i; //ex: "gem2"
		var gemOBJ:Object = name;
		if (background.gemOBJ.hitTestObject(Rose)) {
			background.gemOBJ.visible = false;
			background.gemOBJ.y = 1500;
			background.gemOBJ.gotoAndStop(7);
		}
		
	}

 

if that makes sense

This topic has been closed for replies.
Correct answer kglad

if there are object instances named "gem"+i, use bracket notation to coerce the string to an object:

 

var name:String="gem"+i;

var gemObj:DisplayObject = DisplayObject(background[name]); // assuming background are the gems' parent

 

and because your gems are movieclips, you can be more specific:

 

var gem_mc:MovieClip = MovieClip(background[name]); 

1 reply

kglad
Community Expert
kgladCommunity ExpertCorrect answer
Community Expert
April 20, 2022

if there are object instances named "gem"+i, use bracket notation to coerce the string to an object:

 

var name:String="gem"+i;

var gemObj:DisplayObject = DisplayObject(background[name]); // assuming background are the gems' parent

 

and because your gems are movieclips, you can be more specific:

 

var gem_mc:MovieClip = MovieClip(background[name]);