C# how to use function Object.FindObjectOfType() ?

use javascript:

called: call01.js

function move(){
	
	transform.Translate ( 1*Time.deltaTime,0,0 );
	
	}
	
function display(){
	
	print("We are runing......");
	
	}

base script:

var other: call01;

function Start(){
	
	other=FindObjectOfType (call01);
	if(other){
		
		//print("ok!");
		other.display();
		
		}	
	
	}

function Update () {
	
	if( other ){
		
		other.move();
		
		}
	
}

can run …

use C#:

called: call01_c_sharp.cs

......

	public void move(){
		
		transform.Translate ( 1*Time.deltaTime,0,0 );
		
		}
		
	public void display(){
		
		print("It's Runing............ ");
		
		}

base script:

	public call01_c_sharp other;
	public bool runIO=false;
	
	void Start () {
	
		other=FindObjectOfType (typeof(call01_c_sharp));    //It's error......
	
	}

can’t run.

message:Cannot implicitly convert type ‘UnityEngine.Object’ to ‘call01_c_sharp’.An explicit conversion exists(ary you missing a cast?)


alas!I think mostly it is the data type conversion problem…:frowning: :frowning:
I would like to ask:This question should be how to resolve?

Thanks a lot for any help…

other = FindObjectOfType (typeof(call01_c_sharp)) as call01_c_sharp;

It needs to be cast to the script type, as FindObjectOfType returns an Object.

-Jeremy

:slight_smile: :slight_smile: :slight_smile: Thank …

But , This is the only one solution?
“(call01_c_sharp)” can not use it?

Both of the following examples will work.

other = FindObjectOfType (typeof(call01_c_sharp)) as call01_c_sharp;
other = (call01_c_sharp)FindObjectOfType (typeof(call01_c_sharp));

The difference is that when you use “… as typename” on something that is not of the correct type, the result will simply be set to null, wheras “(typename) …” will throw an error. (But in the above case both are equivalent as FindObjectOfType will never return an object that can’t be converted to the type you are looking for.)

hi…Thank you… :lol: :lol: :lol: