Eegxeta Eegxeta - 3 months ago 15
C# Question

C# keep common functions in seperate cs file can't find namespace

First off I'm only creating this question because I can't make comments in the question that has nearly all the info I need. Here is that question so I don't have to duplicate more than I have to:

Keep common functions in separate cs file? (C#)

So I followed the info Jonesopolis gave in his answer, but it just throws me an error saying it can't find the namespace on the using GeneralStuff; line.

This is the contents of the cs file I would like to use the function from:

using UnityEngine;
using System.Collections;

namespace GeneralStuff
{
public static class GeneralStuff
{
/// <summary>
/// Creates a Unity color object using values 0-255
/// so getting the color right is easier
/// </summary>
/// <param name="r"></param>
/// <param name="g"></param>
/// <param name="b"></param>
/// <returns></returns>
public static Color setColor(float r, float g, float b)
{

if (r != 0)
{
r = r / 255f;
}

if (g != 0)
{
g = g / 255f;
}

if (b != 0)
{
b = b / 255f;
}

Color color = new Color(r, g, b);

return color;
}

}
}


This cs file is in the same folder as the cs file I would like to use this function in. Yes it is a script in Unity project in case that is relevant. I missing something, but I can't figure out what. Can someone help?

Answer

In your second file, you have to have a using statement for the namespace you wish to use:

  • [[ other-file.cs ]]

    using GeneralStuff;
    
    namespace SecondFile {
        public class SecondClass {
            public SecondClass() {
                var something = GeneralStuff.setColor(0f,0f,0f);
            }
        }
    }
    

EDIT: You'll also need to include it in the current project. From this SO answer:

  1. Right-click project and select "Add -> Existing Item"
  2. Navigate to the file you want to add as a link, and select it.
  3. Look at the "Add" button at lower right of the "Add Existing Item" dialog. It has a little drop arrow.
  4. Click that drop arrow. Select "Add as link".
Comments