Итак, в одном скрипте создаются префабы:
C# |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
| public class Board : MonoBehaviour
{
public GameObject Button;
public List<Gem> gems = new List<Gem>();
public List<Gem> gemes = new List<Gem>(36);
public int GridWidth;
public int GridHeight;
public GameObject gemPrefab;
public Gem lastGem;
public Vector3 gem1Start, gem1End, gem2Start, gem2End;
public bool isSwapping = false;
public bool SwapBack = false;
public float startTime;
public float SwapRate = 2;
public Gem gem1, gem2;
public int AmountToMatch = 3;
public bool isMatched = false;
// Use this for initialization
void Start()
{
for (int y = 0; y < GridHeight; y++)
{
for (int x = 0; x < GridWidth; x++)
{
GameObject g = Instantiate(gemPrefab, new Vector3(x, y, 0), Quaternion.identity) as GameObject;
g.transform.parent = gameObject.transform;
gems.Add(g.GetComponent<Gem>());
}
}
gameObject.transform.position = new Vector3(-2.5f, -2f, 0);
} public int plusball(string ButtonColor, string bullColor)
{
int a;
if (ButtonColor == "RedPlusField")
{
if (bullColor == "red")
{
a = 1;
}
else if (ButtonColor == "Blue")
{
a = -1;
}
else if (ButtonColor == "Green")
{
a = -1;
}
else if (ButtonColor == "Grey")
{
a = 0;
}
else if (ButtonColor == "Yellow")
{
a = 1;
}
else
{
a = 0;
}
}
else
{
a = 0;
}
return a;
} |
|
скрипт самого префаба:
C# |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
| public class Gem : MonoBehaviour {
public GameObject gemHolder;
public GameObject sphere;
public GameObject selector;
public GameObject Text;
public bool isSelected = false;
public bool isMatched = false;
public int Health;
string[] gemMats = { "Red", "Blue", "Green", "Grey", "Yellow", "Purple" };
public string color = "";
public List<Gem> Neighbors = new List<Gem>();
void Start () {
CreateGem();
}
public void CreateGem()
{
Destroy(sphere);
color = gemMats[Random.Range(0, gemMats.Length)];
GameObject gemPrrefab = Resources.Load("Prefabs/" + color) as GameObject;
sphere = (GameObject)Instantiate(gemPrrefab,Vector3.zero,Quaternion.identity);
sphere.transform.parent = gemHolder.transform;
sphere.transform.localPosition = Vector3.zero;
Health = Random.Range(1, 6);
isMatched = false;
Text.GetComponent<TextMesh>().text = Health.ToString();
} |
|
Как я пытался это сделать:
1)создал кнопку при нажатии на которую над префабами создавался падающий на них куб, который должен был изменить куб.
скрипт кнопки:
C# |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| public class redplusbutton : MonoBehaviour
{
public string color = "red";
public string bullscolor;
public string bulltext;
public GameObject RedPlusField;
// Use this for initialization
void Start()
{
}
void Update()
{
}
void OnMouseDown()
{
GameObject Red =Instantiate(RedPlusField, new Vector3(0,20,0), Quaternion.identity) as GameObject;
}
} |
|
скрипт падающего куба:
C# |
1
2
3
4
5
6
7
8
9
| void OnCollisionEnter(Collision col)
{
if (col.gameObject.name == "Gem(Clone)")
{
col.gameObject.GetComponent<Gem>().Health +=GetComponent<Board>().plusball("RedPlusField", col.gameObject.GetComponent<Gem>().color);
col.gameObject.GetComponent<Gem>().Text.GetComponent<TextMesh>().text = col.gameObject.GetComponent<Gem>().Health.ToString();
Debug.Log("Box went through!");
}
} |
|
Выдает такую ошибку:
NullReferenceException: Object reference not set to an instance of an object
collissphere.OnCollisionEnter (UnityEngine.Collision col) (at Assets/Resources/Scripts/collissphere.cs:21)
21 строчка
col.gameObject.GetComponent<Gem>().Health +=GetComponent<Board>().plusball("RedPlusField", col.gameObject.GetComponent<Gem>().color);
2) пытался найти все объекты с тегом и изменить у них здоровье
в этом случае единственный метод скрипта кнопки таков:
C# |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| void OnMouseDown()
{
GameObject[] go = GameObject.FindGameObjectsWithTag("Gem");
foreach (GameObject gem in go)
{
bullscolor = gem.GetComponent<Gem>().color;
gem.GetComponent<Gem>().Health += GetComponent<Board>().plusball(color, bullscolor);
bulltext = gem.GetComponent<Gem>().Health.ToString();
gem.GetComponent<Gem>().Text.GetComponent<TextMesh>().text = bulltext;
}
GameObject Red =Instantiate(RedPlusField, new Vector3(0,20,0), Quaternion.identity) as GameObject;
} |
|
Ошибка выскакивала аналогичная.
Пробовал сделать массив из GameObject и присваивать Н-ому члену только что созданный объект, но почему то ошибка из-за выхода за границы массива(хотя создавалось только 2 элемента из 36), попробовал сделать список из создаваемых массивов , но при таком же обращении такая же ошибка что и в первых 2-ух случаях
Очевидно проблема в использовании метода ГетКомпонент , но какая я понять не могу.Помогите нубу пожалуйста.