Unityで何回やり直しても「Can’t add script」というエラーが出るんだけど!泣
どうも、Linです。銭湯で茹で上がりたいです。
Unityでオブジェクトにスクリプトをアタッチしようとすると、

Can’t add script
という怖くて意味不明なエラーが出現しました。

エラーの詳細を読んでみても、
Can’t add script component ‘sample’ because the script class cannot be found. Make sure that there are no compile errors and that the file name and class name match.
さっぱりなんのことだかわかりません笑
どうしたらいいかわからず質問できる友もいませんでしたのでググってみると、
スクリプト内のクラス名と、スクリプト名が異なること
が原因だということがうっすらとわかってきました。
【参考にしたサイト】
どのサイトも口を揃えて唱えていた対処法は、
アタッチしたいC#ファイルのクラス名をファイル名と同じにする
です。
ぼくもこれで一発でエラーが解消しました。
C#ファイル名は「Sample.cs」でした。
エラーが出たのは下のようなコード。
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class NewBehaviourScript : MonoBehaviour { public Text text; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
こいつを、
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Sample : MonoBehaviour { public Text text; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
に変えるだけオッケーでした。
つまり、
NewBehaviorScript
というクラス名をC#スクリプト同じ、
Sample
に変更してあげているわけです。
「Can’t add script」という謎のエラーでお困りの方はクラス名をチェックしてみてくださいね。
それでは!
Lin

おそらく、ブロガー。
今年でフリーランス 6年目。