Can't find script in GameObject with GetComponent ("The type or namespace name could not be found")

Hello everyone!

Sorry if I’m a little bit off with the terminology here, but I’m kinda a beginner.

So, I’m trying to run a method from a certain GameObject (“RailCylinder”) from a different GameObject (“RailGun”), but I just can’t “find” it.

My steps are:

1) Created a script in GameObject "RailCylinder":

2) In the script, I created the public method GetsFired()

3) Now it’s when I get the problem. When I try to call this method from the other GameObject “RailGun”, it can not find the script component and keeps getting the error (“The type or namespace name could not be found”):

I have no idea why this is happening. I’ve done this before and it has always worked, I really don’t know what I’m doing in a different way this time. Could you please orientate me a little bit on this?

Thanks in advance!

Try to change GameObject to RailCylinder and then call the function like this:

public RailCylinder railCylinder;

void createCylinder(/*stuff*/)
{
 railCylinder.GetsFired();
}

You can also make sure with this that you insert only an Object with the RailCylinder script attached.

public RailCylinder railCylinder;

When I try to do that I get the same error (“The type or namespace name could not be found”) :frowning:

Is either script inside a namespace? (Can you share the top part of each file?)

Sure, you mean this?

RailGun.cs:

using System;
using System.Collections.Generic;
using UnityEngine;


public class RailGun : MonoBehaviour
{
    //railgun properties
    public float damage = 3f;
    public float fireRate = 1f;
    public float impactForce = 30f;
    public int amountSlugs = 10;   
    public float range = 500f;
    public float blastRadius = 2f;
    public float blastRadiusDamage = 50f;
    public float railgunThickness = .15f;

    //useful scene objects
    public GameObject weaponHolder;
    public Camera fpsCam;
    public GameObject railgunBarrelExit;
    public LineRenderer lineRenderer;
    public GameObject railCylinder;   

    //particles
    public ParticleSystem shotLightLevel1;
    public ParticleSystem shotLightLevel2;
    public ParticleSystem shotLightLevel3;
    public ParticleSystem shotLightLevel4;
    public ParticleSystem shotLightLevel5;

    public ParticleSystem impactLevel1;
    public ParticleSystem impactLevel2;
    public ParticleSystem impactLevel3;
    public ParticleSystem impactLevel4;
    public ParticleSystem impactLevel5;

    public ParticleSystem radiusDamageBlastLevel1;
    public ParticleSystem radiusDamageBlastLevel2;
    public ParticleSystem radiusDamageBlastLevel3;
    public ParticleSystem radiusDamageBlastLevel4;
    public ParticleSystem radiusDamageBlastLevel5;

    public ParticleSystem blood;

    //audio
    public AudioSource rgAudio;
   
   
    //for the animation
    public bool railgunJustFired = false;   
    public float whenRailGunFired = 0f;
    public float powerLevelWhenFired = 0;
    public float currentRailLength = 0;
    private float nextTimeToFire = 0f;
    public int depletionCounter = 0;   
    public int rgAnimationLength = 100;

RailCylinder.cs:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RailCylinder : MonoBehaviour
{
    public bool railgunJustFired;
    public GameObject railCylinder;
    public float nextTimeToFire;
    public float fireRate;
    public float powerLevelWhenFired;
    public float railgunThickness;
    public float currentRailLength;

I don’t see anything wrong there. Did you remember to save the RailCylinder file, and do you have any other compile errors in your Unity console*?*

Judging by this screenshot RailCylinder has unsaved changes:

1 Like

Yes, I saved everything.

Regarding errors, these 2 are the only ones that show up in the console (haven’t figured these out yet, but I don’t think they are related to this issue):

UnassignedReferenceException: The variable m_Target of TargetFieldOfView has not been assigned.
You probably need to assign the m_Target variable of the TargetFieldOfView script in the inspector.
UnityEngine.Transform.get_position () (at :0)
UnityStandardAssets.Cameras.TargetFieldOfView.FollowTarget (System.Single deltaTime) (at Assets/Standard Assets/Cameras/Scripts/TargetFieldOfView.cs:37)
UnityStandardAssets.Cameras.AbstractTargetFollower.FixedUpdate () (at Assets/Standard Assets/Cameras/Scripts/AbstractTargetFollower.cs:46)

(this one is the player controller)
NullReferenceException: Object reference not set to an instance of an object
UnityStandardAssets.Characters.FirstPerson.FirstPersonController.OnControllerColliderHit (UnityEngine.ControllerColliderHit hit) (at Assets/Standard Assets/Characters/FirstPersonCharacter/Scripts/FirstPersonController.cs:257)
UnityEngine.CharacterController:Move(Vector3)
CPMPlayer:Update() (at Assets/Scripts/CPMPlayer.cs:156)

To follow up on that - does it compile in Unity? Visual Studio installs are sometimes just straight up broken.

Edit: Also, what’s the exact error message?

Well, I feel stupid now… the error was showing up in Visual Studio, so I assumed it wasn’t working, but yeah, now I tried it in Unity and it’s working just fine :roll_eyes:

Thanks a lot for your help guys!

Hey sorry all buy I’m having the issue everyone thought was happening, and I don’t know how to fix it.
I have a script where everything is in a namespace. Within that script there is a raycast, where I need to access the hit object. I then want to go into the hit object, and getcomponent for a script, and change a variable in there (a gun shoot, hits an object, changes its health).
The problem is the bullet’s raycast is within a namespace, so using the getcomponent is giving me errors. How do I do getcomponent from within a namespace, to access things in another object, with a normal script, in a normal monobehavior?

GetComponent<NameOfNamespace.NameOfComponent>()
or
using NameOfNamespace; on top of the script (together with all the other using statements for namespaces, like UnityEngine etc.)

1 Like

I’m totally a noob, so I could be wrong, but I think you have the situation backwards. The script I want to reference does not have a namespace. The script I want to reference it from does have a namespace. So my getcomponent is within a namespace, wanting to access something in a normal script. So I believe that is backwards of what you’re describing.
Like, if I were to write GetComponent<NameOfNamespace.NameOfComponent>(), there would be no namespace to put. I’m trying to access it FROM code that is within a namespace (I actually wouldn’t think this would cause an issue, but apparently it does).
Know what I mean? Or am I totally wrong?

Namespaces are purely organisational. A class not being in a namespace and one being inside it should make no difference. You should freely be able to access classes not inside a namespace from classes inside a namespace, so long as they’re in the same assembly, or the latter has a reference to the assembly of the former.

Either your Visual Studio install isn’t right (might need to regenerate project files), or the class you’re trying to reference is in a different assembly.

What’s the error you’re getting? Always post the text of the error, that makes it a ton easier to help you.

Then it should just work ™ to reference the script directly. as spiney199 is saying, they’re just organizational.

A class named ClassName inside a namespace named NamespaceName has the full name NamespaceName.ClassName. If it’s not in a namespace, it just named ClassName.

If you’re using the type ClassName, the compiler will look for any type named ClassName, or NamespaceName.ClassName for all the namespaces that is in scope (with using), and for any namespace you’re currently in. So in the example here:

using Foo;
namespace Bar {
    public class MyClass {
        public OtherClass o;
    }
}

OtherClass will be found if it’s got no namespace, if it’s in the namespace Foo (as it’s imported) or if it is in the namespace Bar (as we’re already inside that scope).

Sorry I thought I did post the error message! My bad. Here it is.

Severity    Code    Description    Project    File    Line    Suppression State
Error    CS0246    The type or namespace name 'BodyPartId' could not be found (are you missing a using directive or an assembly reference?)

And yeah what both of you are saying, that’s what I would think too! Here’s the first portion of the script, to show how it’s doing namespace and class stuff

namespace HurricaneVR.Framework.Weapons.Guns
{
    public class HVRGunBase : HVRDamageProvider
    {

It’s possible the one with the namespace is in a different assembly, because I don’t fully understand what that means (sorry for my noobishness).
The code I’m using to change the variable is really straightforward, and was working in a different place just fine. It was only when I put it in this namespace script that it had the error. Here’s the line of code if you want to look at it. I’ve deleted stuff that wouldn’t be relevant.

private void UpdateTrackedBullets()
        {
            for (int i = 0; i < _objects.Count; i++)
            {
                var tracker = _objects[i];
                var bullet = tracker.Bullet;
                if (bullet.activeSelf)
                {
                    var speed = _objects[i].Speed;
                    var distance = speed * Time.deltaTime;

                    if (Physics.Raycast(bullet.transform.position, tracker.Direction, out var hit, distance, HitLayerMask, QueryTriggerInteraction.Ignore))
                    {
                        OnHit(hit, tracker.Direction);
                        bullet.SetActive(false);
                        _objects[i].SetRenderersActive(false);

                        if (hit.transform.gameObject.tag == "Enemy")
                        {

                            if (hit.transform.gameObject.GetComponent<BodyPartId>().Is01VeryWeak)
                            {
                                ThisDamage = BulletDamage * 1;
                            }

The problematic part is the hit.transform.gameObject.GetComponent()., and then similar things down below that. It’s as though it’s not recognizing any of my scripts as possible things to find. I’m guessing it’s the assembly reference thing? Do I need to tell it to reference a different assembly or something?

As I see it, there is no noobismishness about assemblies at all.
People who talk about it are usually far from mastering it and I’ve seen people who do not know about it and release anyway.

Here in a short version:

  1. You can go into one of your folders inside your unity project and right click → create → assembly definition
  2. You have created some kind of box now. Unity will look at it and when something changes inside, Unity is now aware that it has to recompile everything in that box instead of everything everything.
  3. You can created seperated areas in your project like that and you will be able to go into testing more quickly (e.g.
    one assembly definition for your unity store/external content)
  4. Everything needs a reference now when you need something from another box. You need to tell Unity in which box it has to look or it will tell you: ‘X’ could not be found (are you missing a using directive or an assembly reference?

I had a problem where I could not access a script called ‘VRMLookAtHead’. After a lot of struggling I realized that it is part of something called ‘VRM.dll’. I added a line ‘using VRM;’ (at the very beginning, you should have imports or

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

here). Now it works as my problem was referring to the using directive part.
Side information: I wanted a diver to stop rotating his head while swimming. No he is flying through the air but I am getting there.

You can find further information about assemblies by watching a video on yt (HYqOSkHI674).
Change the last few symbols of the URL (top bar in browser) when you have the tab open already.

I hope I could help you a little. Have a nice day and good luck.