質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
C#

C#はマルチパラダイムプログラミング言語の1つで、命令形・宣言型・関数型・ジェネリック型・コンポーネント指向・オブジェクティブ指向のプログラミング開発すべてに対応しています。

Unity3D

Unity3Dは、ゲームや対話式の3Dアプリケーション、トレーニングシュミレーション、そして医学的・建築学的な技術を可視化する、商業用の開発プラットフォームです。

Unity

Unityは、Unity Technologiesが開発・販売している、IDEを内蔵するゲームエンジンです。主にC#を用いたプログラミングでコンテンツの開発が可能です。

Q&A

1回答

1971閲覧

Unity GetComponentについて

Tats.N

総合スコア62

C#

C#はマルチパラダイムプログラミング言語の1つで、命令形・宣言型・関数型・ジェネリック型・コンポーネント指向・オブジェクティブ指向のプログラミング開発すべてに対応しています。

Unity3D

Unity3Dは、ゲームや対話式の3Dアプリケーション、トレーニングシュミレーション、そして医学的・建築学的な技術を可視化する、商業用の開発プラットフォームです。

Unity

Unityは、Unity Technologiesが開発・販売している、IDEを内蔵するゲームエンジンです。主にC#を用いたプログラミングでコンテンツの開発が可能です。

0グッド

0クリップ

投稿2017/03/23 21:30

こんにちは。いつもありがとうございます。
Unity、C#ともに初心者でわからないので質問させてください。

#あるScriptから他のScript内のオブジェクトを削除するには

GetComponent<TexturePainter> ();でアクセスできると思っていたのですが、ある時はNullを、またある時はGetComponentを使ったところから下のコードが実行されません。

1つ目のコードが適応されている3dオブジェクトをクリックすると2つ目のコード内のbrushContainer内の子要素を削除したいのですが、どうすれば良いのでしょうか??

C#

1using System.Collections; 2using System.Collections.Generic; 3using UnityEngine; 4 5public class EraseCanvas : MonoBehaviour { 6 //int brushCounter=0,MAX_BRUSH_COUNT=1000; //To avoid having millions of brushes 7 public Material baseMaterial; // The material of our base texture (Were we will save the painted texture) 8 public GameObject bContainer; //The cursor that overlaps the model and our container for the brushes painted 9// // Use this for initialization 10// void Start () { 11// 12// } 13 14 // Update is called once per frame 15 void Update(){ 16// Debug.Log (brushContainer); 17// Debug.Log (GetComponent<TexturePainter> ()); 18// Debug.Log (brushContainer); 19 if(Input.GetMouseButtonDown(0)){ 20 Transform cam = Camera.main.transform; 21 var ray = new Ray(cam.position, cam.forward); 22 RaycastHit hit; 23 if(Physics.Raycast (ray, out hit)){ 24 var e = hit.transform.GetComponent<EraseCanvas> (); 25 if (e != null) { 26 Debug.Log ("|----------------------------------"); 27 Debug.Log (bContainer.GetComponent<TexturePainter>().brushContainer); 28 Debug.Log ("----------------------------------|"); 29 foreach (Transform child in bContainer.GetComponent<TexturePainter> ().brushContainer.transform) {//Clear brushes 30 Destroy(child.gameObject); 31 Debug.Log ("hi again"); 32 } 33 } 34 } 35 } 36 } 37 38 39 40 void ClearCanvas(){ 41 //brushCounter=0; 42 //System.DateTime date = System.DateTime.Now; 43// //RenderTexture.active = canvasTexture; 44// Texture2D tex = new Texture2D(canvasTexture.width, canvasTexture.height, TextureFormat.RGB24, false); 45// tex.ReadPixels (new Rect (0, 0, canvasTexture.width, canvasTexture.height), 0, 0); 46// tex.Apply (); 47 //RenderTexture.active = null; 48 //baseMaterial.mainTexture =tex; //Put the painted texture as the base 49 50 //StartCoroutine ("SaveTextureToFile"); //Do you want to save the texture? This is your method! 51// Invoke ("ShowCursor", 0.1f); 52 } 53 54} 55

2.呼び出そうとしているオブジェクトがあるコード

C#

1/// <summary> 2/// CodeArtist.mx 2015 3/// This is the main class of the project, its in charge of raycasting to a model and place brush prefabs infront of the canvas camera. 4/// If you are interested in saving the painted texture you can use the method at the end and should save it to a file. 5/// </summary> 6 7 8using UnityEngine; 9using UnityEngine.UI; 10using System.Collections; 11 12 13public enum Painter_BrushMode{PAINT,DECAL}; 14public class TexturePainter : MonoBehaviour { 15 public GameObject brushCursor,brushContainer; //The cursor that overlaps the model and our container for the brushes painted 16 public Camera sceneCamera,canvasCam; //The camera that looks at the model, and the camera that looks at the canvas. 17 public Sprite cursorPaint,cursorDecal; // Cursor for the differen functions 18 public RenderTexture canvasTexture; // Render Texture that looks at our Base Texture and the painted brushes 19 public Material baseMaterial; // The material of our base texture (Were we will save the painted texture) 20 21 Painter_BrushMode mode; //Our painter mode (Paint brushes or decals) 22 float brushSize=1.0f; //The size of our brush 23 public Color brushColor; //The selected color 24 int brushCounter=0,MAX_BRUSH_COUNT=1000; //To avoid having millions of brushes 25 bool saving=false; //Flag to check if we are saving the texture 26 27 28 void Update () { 29 //brushColor = ColorSelector.GetColor (); //Updates our painted color with the selected color 30 // brushColor = customBrushColor; // This is the brush color 31 if (Input.GetMouseButton(0)) { 32 DoAction(); 33 } 34 UpdateBrushCursor (); 35 } 36 37 //The main action, instantiates a brush or decal entity at the clicked position on the UV map 38 void DoAction(){ 39 if (saving) 40 return; 41 Vector3 uvWorldPosition=Vector3.zero; 42 if(HitTestUVPosition(ref uvWorldPosition)){ 43 GameObject brushObj; 44 if(mode==Painter_BrushMode.PAINT){ 45 46 brushObj=(GameObject)Instantiate(Resources.Load("TexturePainter-Instances/BrushEntity")); //Paint a brush 47 brushObj.GetComponent<SpriteRenderer>().color=brushColor; //Set the brush color 48 } 49 else{ 50 brushObj=(GameObject)Instantiate(Resources.Load("TexturePainter-Instances/DecalEntity")); //Paint a decal 51 } 52 brushColor.a=brushSize*2.0f; // Brushes have alpha to have a merging effect when painted over. 53 brushObj.transform.parent=brushContainer.transform; //Add the brush to our container to be wiped later 54 brushObj.transform.localPosition=uvWorldPosition; //The position of the brush (in the UVMap) 55 brushObj.transform.localScale=Vector3.one*brushSize;//The size of the brush 56 } 57 brushCounter++; //Add to the max brushes 58 if (brushCounter >= MAX_BRUSH_COUNT) { //If we reach the max brushes available, flatten the texture and clear the brushes 59 brushCursor.SetActive (false); 60 saving=true; 61 Invoke("SaveTexture",0.1f); 62 63 } 64 } 65 //To update at realtime the painting cursor on the mesh 66 void UpdateBrushCursor(){ 67 Vector3 uvWorldPosition=Vector3.zero; 68 if (HitTestUVPosition (ref uvWorldPosition) && !saving) { 69 brushCursor.SetActive(true); 70 brushCursor.transform.position =uvWorldPosition+brushContainer.transform.position; 71 } else { 72 brushCursor.SetActive(false); 73 } 74 } 75 //Returns the position on the texuremap according to a hit in the mesh collider 76 bool HitTestUVPosition(ref Vector3 uvWorldPosition){ 77 RaycastHit hit; 78 // Vector3 cursorPos = new Vector3 (Input.mousePosition.x, Input.mousePosition.y, 0.0f); 79 80 Vector3 cursorPos = new Vector3 (Screen.width/2, Screen.height/2, 0.0f); 81 82 //Debug.Log("Screen.width/2 " + Screen.width/2); 83 //Debug.Log("0.5f " + 0.5f); 84 85 Ray cursorRay = sceneCamera.ScreenPointToRay (cursorPos); 86 87 if (Physics.Raycast(cursorRay,out hit,200)){ 88 MeshCollider meshCollider = hit.collider as MeshCollider; 89 90 var e = hit.transform.GetComponent<canvasScript> (); 91 92 if (meshCollider == null || meshCollider.sharedMesh == null){ 93 return false; 94 }else if(e != null){ 95 Vector2 pixelUV = new Vector2(hit.textureCoord.x,hit.textureCoord.y); 96 uvWorldPosition.x=pixelUV.x-canvasCam.orthographicSize;//To center the UV on X 97 uvWorldPosition.y=pixelUV.y-canvasCam.orthographicSize;//To center the UV on Y 98 uvWorldPosition.z=0.0f; 99 return true; 100 } 101 } 102 else{ 103 return false; 104 } 105 return false; 106 107 } 108 109 110 111 //Sets the base material with a our canvas texture, then removes all our brushes 112 void SaveTexture(){ 113 brushCounter=0; 114 System.DateTime date = System.DateTime.Now; 115 RenderTexture.active = canvasTexture; 116 Texture2D tex = new Texture2D(canvasTexture.width, canvasTexture.height, TextureFormat.RGB24, false); 117 tex.ReadPixels (new Rect (0, 0, canvasTexture.width, canvasTexture.height), 0, 0); 118 tex.Apply (); 119 RenderTexture.active = null; 120 baseMaterial.mainTexture =tex; //Put the painted texture as the base 121 foreach (Transform child in brushContainer.transform) {//Clear brushes 122 Destroy(child.gameObject); 123 } 124 //StartCoroutine ("SaveTextureToFile"); //Do you want to save the texture? This is your method! 125 Invoke ("ShowCursor", 0.1f); 126 } 127 //Show again the user cursor (To avoid saving it to the texture) 128 void ShowCursor(){ 129 saving = false; 130 } 131 132 ////////////////// PUBLIC METHODS ////////////////// 133 134 public void SetBrushMode(Painter_BrushMode brushMode){ //Sets if we are painting or placing decals 135 mode = brushMode; 136 brushCursor.GetComponent<SpriteRenderer> ().sprite = brushMode == Painter_BrushMode.PAINT ? cursorPaint : cursorDecal; 137 } 138 public void SetBrushSize(float newBrushSize){ //Sets the size of the cursor brush or decal 139 brushSize = newBrushSize; 140 brushCursor.transform.localScale = Vector3.one * brushSize; 141 } 142 143 ////////////////// OPTIONAL METHODS ////////////////// 144 145 #if !UNITY_WEBPLAYER 146 IEnumerator SaveTextureToFile(Texture2D savedTexture){ 147 brushCounter=0; 148 string fullPath=System.IO.Directory.GetCurrentDirectory()+"\\UserCanvas\\"; 149 System.DateTime date = System.DateTime.Now; 150 string fileName = "CanvasTexture.png"; 151 if (!System.IO.Directory.Exists(fullPath)) 152 System.IO.Directory.CreateDirectory(fullPath); 153 var bytes = savedTexture.EncodeToPNG(); 154 System.IO.File.WriteAllBytes(fullPath+fileName, bytes); 155 Debug.Log ("<color=orange>Saved Successfully!</color>"+fullPath+fileName); 156 yield return null; 157 } 158 #endif 159} 160

わかる方おられましたら、ご教授願います。よろしくお願いします。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

「クリックしたオブジェクトに付いているEraseCanvas」が対象であるなら、
foreach (Transform child in bContainer.GetComponent<TexturePainter> ().brushContainer.transform) {
の部分は、bContainerの前にe.を入れた
foreach (Transform child in e.bContainer.GetComponent<TexturePainter> ().brushContainer.transform) {
になります。
(eが無いと「自分自身のbContainer」を対象にしようとします)

ちなみにここを直しても、以下の条件下でエラーが発生します。

  • bContainerがnullの時
  • bContainerにTexturePainterが付いていない時
  • bContainerのTexturePainterのbrushContainerがnullの時

これはUnityの仕様です。
なので適宜nullチェックを挟むか、絶対にnullが発生しないような構造とする
(スクリプト上で確実に変数にオブジェクトを入れる等)必要があるかと思います。

投稿2017/03/24 09:34

sakura_hana

総合スコア11427

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問