error CS0120: An object reference is required to access non-static member
I'm working on a game with a ship that needs a rigidbody to handle smacking into things.
Spaceship
Ship
thrusters: Thruster 1 Thruster 2 Thruster 3
Spaceship has the script + rigidbody Ship has the mesh collider from model / is the model
I honestly can't find anything to help me figure out why it doesn't seem to want to let me use the rigidbody component or reference to the gameobject the script itself is attached to. I've tried a dozen different combinations of doing the same thing.
ShipController.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ShipController : MonoBehaviour
{
public int maxSpeed = 70;
public int minSpeed = 10;
public float rotationSpeed = 150;
public int currrentSpeed = 30;
private GameObject[] thrusters;
private Rigidbody rb;
public GameObject ship;
void Start(){
thrusters = GameObject.FindGameObjectsWithTag("Thruster");
ship = Component.gameObject;
Rigidbody rb = ship.GetComponent<Rigidbody> ();
}
void LateUpdate()
{
//Controls
if (Input.GetKey(KeyCode.A))
transform.Rotate(0, 0, Time.deltaTime*rotationSpeed);
else if (Input.GetKey(KeyCode.D))
transform.Rotate(0, 0, -Time.deltaTime*rotationSpeed);
if (Input.GetKey(KeyCode.W))
transform.Rotate(Time.deltaTime*rotationSpeed, 0, 0);
else if (Input.GetKey(KeyCode.S))
transform.Rotate(-Time.deltaTime*rotationSpeed, 0, 0);
//Min speed
if (Input.GetKey(KeyCode.Space)){
currrentSpeed = minSpeed;
Thruster(0.2f);
}//Max speed
else{
currrentSpeed = maxSpeed;
Thruster(5f);
}
//transform.Translate(Vector3.forward * Time.deltaTime*currrentSpeed);
rb.velocity = (Vector3.forward * Time.deltaTime*currrentSpeed);
}
void Thruster(float intensity){
foreach (GameObject thruster in thrusters)
{
thruster.GetComponent<LensFlare>().brightness = intensity;
}
}
}
$$anonymous$$anaged to fix it, kind of. The error I was getting is gone and I'm moving but I'm not moving how I want, so.. technically fixed.
Old code pieces: GameObject ship = Component.gameObject Rigidbody rb = ship.GetComponent ();
New code pieces: GameObject ship = GameObject.FindWithTag("Player"); rb = ship.GetComponent ();
So the object is set and the rigidbody isn't declared twice. Now to go fix the movement..
Answer by hexagonius · Jan 24, 2016 at 09:01 AM
This can't be right:
ship = Component.gameObject;
its either just gameobject, or some GameObject.Find
Originally it was but that didn't work so I tied that, which of course didn't work either.
Your answer
Follow this Question
Related Questions
How do I run an animation then destroy a game object? 1 Answer
How can i change bool of other gameobject? 1 Answer
I need quick help with my C# code GetComponent! 1 Answer
this.GetComponent() won't return gameObject? How to get it without using this.gameObject? 3 Answers
Reference a script on a gameobject that is disabled in scene 0 Answers