Julio Andryanto
Julio Andryanto

Reputation: 82

Get all same scripts that attached in scene's gameobjects and store its into array, using c#

I need to get all same scripts in scene and then process it in another script is possible to do that??
Here is what I tried so far, but unity throws the below error when using it:

ScrollingBackgroundScript[] scrollingObjects = FindObjectsOfType (typeof(ScrollingBackgroundScript)) as ScrollingBackgroundScript;  

The error statement from unity is:

error CS0039: Cannot convert type UnityEngine.Object[] to ScrollingBackgroundScript via a built-in conversion

Upvotes: 1

Views: 757

Answers (2)

Roberto
Roberto

Reputation: 11933

Based on your comment (getting only one instead of multiple game objects), I think it may be the case that the other objects are inactive. FindObjectsOfType doesn't find inactive objects :)

One solution to this is to use Resources.FindObjectsOfTypeAll:

var scrollingObjects = Resources.FindObjectsOfTypeAll<ScrollingBackgroundScript>();

Please notice that it can end up returning more things than you want! (check the documentation).

Upvotes: 1

Jinjinov
Jinjinov

Reputation: 2683

you forgot the []

ScrollingBackgroundScript[] scrollingObjects = FindObjectsOfType (typeof(ScrollingBackgroundScript)) as ScrollingBackgroundScript[];

Upvotes: 0

Related Questions