Answer the question
In order to leave comments, you need to log in
Camera doesn't contain a definition for "main"?
I am writing a 2D platformer, I got to the point where I need to make weapons. I am writing a script, I wrote everything as needed, but unity gives out that Camera does not contain a definition for "main" (camera does not contain a definition for "main").
What to do? Help.
Here is the script:
using UnityEngine;
using System.Collections;
public class FireScript2D : MonoBehaviour
{
public float speed = 10; // скорость пули
public Rigidbody2D bullet; // префаб нашей пули
public Transform gunPoint; // точка рождения
public float fireRate = 1; // скорострельность
public bool facingRight = true; // направление на старте сцены, вправо?
public Transform zRotate; // объект для вращения по оси Z
// ограничение вращения
public float minAngle = -40;
public float maxAngle = 40;
private float curTimeout, angle;
private int invert;
private Vector3 mouse;
void Start()
{
if (!facingRight) invert = -1; else invert = 1;
}
void SetRotation()
{
Vector3 mousePosMain = Input.mousePosition;
mousePosMain.z = Camera.main.transform.position.z;
mouse = Camera.main.ScreenToWorldPoint(mousePosMain);
Vector3 lookPos = mouse - transform.position;
angle = Mathf.Atan2(lookPos.y, lookPos.x * invert) * Mathf.Rad2Deg;
angle = Mathf.Clamp(angle, minAngle, maxAngle);
zRotate.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
void Update()
{
if (Input.GetMouseButton(0))
{
Fire();
}
else
{
curTimeout = 1000;
}
if (zRotate) SetRotation();
if (angle == maxAngle && mouse.x < zRotate.position.x && facingRight) Flip();
else if (angle == maxAngle && mouse.x > zRotate.position.x && !facingRight) Flip();
}
void Flip() // отражение по горизонтали
{
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
invert *= -1;
transform.localScale = theScale;
}
void Fire()
{
curTimeout += Time.deltaTime;
if (curTimeout > fireRate)
{
curTimeout = 0;
Vector3 direction = gunPoint.position - transform.position;
Rigidbody2D clone = Instantiate(bullet, gunPoint.position, Quaternion.identity) as Rigidbody2D;
clone.velocity = transform.TransformDirection(direction.normalized * speed);
clone.transform.right = direction.normalized;
}
}
}
Answer the question
In order to leave comments, you need to log in
Camera.main is a shortcut for getting the camera with the "MainCamera" tag. Those. these two lines are the same:
// эта строка
GameObject.Find("MainCamera").GetComponent<Camera>();
// и эта строка
Camera.main;
// одно и то же
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question