Hi Guys,
I’m new in unity and i’m developing my first game. But i need your help to solve this issue.
I have two script. A is attached to a prefab object A and B the second one is attached to another prefab object B
What i need is to access the script B from A. I used this method in the A script to find script in the object B
B_PrefabScript temp;
temp = GameObject.Find (“B_PrefabObject”).GetComponent<B_PrefabScript> ();
But i can’t find anything and in the editor the name of the script “B_PrefabScript” is always red, it doesn’t find anything.
All my script are in a folder called script.
Can you help me
Thanks a lot
R.
Where the scripts are doesn’t matter. For your case, they need to be attached to an object that exists in the scene. You may have a prefab set up, but unless it exists in the scene (in the hierarchy) you won’t find anything. Prefabs are, as far as I’m aware, primarily to make instantiating new objects with components and presets easier.
Yes, i did my prefab called Character with some scripts attached and i imported it in the scene hierarchy
So i’m using character to find the scripts attached. Something like that
B_PrefabScript temp;
temp = GameObject.Find (“Character”).GetComponent<B_PrefabScript> ();
But as i said i can’t find the script that is always red.
Is it the correct way to do that?
if you are trying to get a reference to a script on the same gameObject you just use
ScriptB scriptB = GetComponent<ScriptB>();
// or more verbose but the same thing
ScriptB scriptB = gameObject.GetComponent<ScriptB>();
if it’s on a child you can use GetComponentInChildren etc.
Find(“…”) looks through the scene (or hierarchy if given an instance to run on) looking for the gameobject’s (or children’s) name that matches the given string. If you are instantiating the prefab through code it will by default be called “Character (clone)” which isn’t going to match “Character”.
I want to show you a quick example. I imported the CharacterRobotBoy prefab in the hierarchy (you can find it on standardAssets/2d/prefab) and then i created another gameObject in the hierarchy called test. I attached this script to test game object:
using UnityEngine;
using System.Collections;
using UnityEngine;
using System.Collections;
public class test : MonoBehaviour
{
PlatformerCharacter2D scriptB;
// Use this for initialization
void Start ()
{
scriptB = GetComponent ();
print (scriptB);
}
}
PlatformerCharacter2D is the script that you can find on the CharacterRobotBoy prefab.
What i want to do is access to the script, but in monodevelop the script is always red…it doesn’t find nothing.
Hope it is more clean