UnityC#のブロック配置スクリプトで参照渡しの挙動について

このQ&Aのポイント
  • Vector3 position = block.transform.positionで参照を渡しているため、block.transform.position = position;が必要ないと思いましたが、同じ位置にブロックが生成されました。
  • 参照を渡しているため、position.x = -(BLOCK_NUM_X/2.0f - 0.5f) + x;とposition.y = -0.5f - y;でblock.transform.positionの中身が書き換わっていると思いましたが、違うようです。
  • なぜ同じ位置にブロックが生成されるのか、参照渡しの挙動について教えてください。
回答を見る
  • ベストアンサー

UnityC#の質問です!

プログラミング初心者です。 ブロックを5*9で並べるスクリプトなのですが。 using UnityEngine; using System.Collections; public class SceneControl : MonoBehaviour { public static int BLOCK_NUM_X = 9; public static int BLOCK_NUM_Y = 5; public GameObject BlockPrefab = null; public BlockControl[,] blocks; void Start() { // ブロックを生成、配置する. this.blocks = new BlockControl[BLOCK_NUM_X, BLOCK_NUM_Y]; int color_index = 0; for(int y = 0;y < BLOCK_NUM_Y;y++) { for(int x = 0;x < BLOCK_NUM_X;x++) { //BlockPrefabをGameobjectにキャストする GameObject game_object = Instantiate(this.BlockPrefab) as GameObject; BlockControl block = game_object.GetComponent<BlockControl>(); this.blocks[x, y] = block; // Vector3 position = block.transform.position; position.x = -(BLOCK_NUM_X/2.0f - 0.5f) + x; position.y = -0.5f - y; block.transform.position = position; block.SetColor((BlockControl.COLOR)color_index); // color_index = Random.Range(0, (int)BlockControl.COLOR.NORMAL_COLOR_NUM); } } // } } で、 Vector3 position = block.transform.position; position.x = -(BLOCK_NUM_X/2.0f - 0.5f) + x; position.y = -0.5f - y; block.transform.position = position; の部分についてなのですが、Vector3 position = block.transform.position;で参照を渡しているので、block.transform.position = position;が必要ないと思い、コメントアウトした所、同じ位置にブロックが生成されてしまいました。 参照を渡していいるため position.x = -(BLOCK_NUM_X/2.0f - 0.5f) + x; position.y = -0.5f - y; の部分で、block.transform.positionの中身が書き換わっていると思ったのですが違うのですか??

質問者が選んだベストアンサー

  • ベストアンサー
  • Picosoft
  • ベストアンサー率70% (274/391)
回答No.1

Unityのリファレンスを見たところ、Vector3はクラスではなく構造体のようです。 https://docs.unity3d.com/Documentation/ScriptReference/Vector3.html 構造体は値型であるため、 他の変数に代入する際は「参照のコピー」ではなく「値のコピー」となります。 例) struct Point{  public int x;  public int y;  public string ToString(){   return string.Format("x={0}, y={1}",x, y);  } } Point p1 = new Point(); Debug.Log(p1.ToString()); //x=0, y=0 Point p2 = p1; p2.x = 1; p2.y = 2; Debug.Log(p1.ToString()); //x=0, y=0 ←「値のコピー」なので、p2のプロパティを変えてもp1には影響しない Debug.Log(p2.ToString()); //x=1, y=2

omoumou13
質問者

お礼

回答ありがとうございます! なるほど! 勝手にクラスだと思ってました。

関連するQ&A

  • Unityの質問です。

    ボタンを押すと、キャラクターの真後ろにオブジェクトが出現するようにしたいのですが、 using UnityEngine; using System.Collections; [ExecuteInEditMode()] public class GUIController : MonoBehaviour { public CharacterController characterController; public GameObject character; public GameObject domino; private Vector3 objPosition; // Use this for initialization void Start () { objPosition = new Vector3 (0, 0, 0); } void OnGUI(){ if(GUI.Button(new Rect(600, Screen.height - 160, 120, 120), "おす")){ Debug.Log("ぼたん"); float x = characterController.transform.localPosition.x; float y = characterController.transform.localPosition.y + 0.5f; float z = characterController.transform.localPosition.z - 0.64f; objPosition.Set(x, y, z); Debug.Log (x+","+y+","+z); GameObject domino_prefab = (GameObject)Instantiate(domino,objPosition, characterController.transform.rotation); } } } こうしてみたのですが、うまくキャラクターの真後ろにオブジェクトが出てきてくれません。 どなたか助けてください!

  • UNITY Float型の接尾辞fって

    UNITYに限ったものではないのですが、Float型の接尾辞fについて Wikiやhttp://www.wisdomsoft.jp/40.html/を見てみたのですが ちょっと難しく理解できません。fってどのような時に使うのでしょうか? Vector3 構造体のコンストラクタの部分で public Vector3(float x, float y, float z)   ←となっていますが、 Vector3 v = new Vector3(765, 961, 876); ←fはついていないですし。 またUNITYのTransformで PositionをX=0.5、Y=0.5、Z=0.5とするのと、X=0.5f、Y=0.5f、Z=0.5fとするのと位置が全然違います。 分かりやすい説明、サイトなどあれば教えてください

  • 深度画像をクラスとして定義する方法について教えて

    VS C++2010を用いて、kinect for Xboxから読み取った深度画像(IplImage *SdepthImg)の データをクラスにする方法を教えていただけないでしょうか。 以下のソース[1]として定義しております。また、深度画像をこのクラスに入れて、以下のソース[2]を用いて深度画像の3次元座標情報を入手するつもりです。 クラスの定義は [1] class Object { private: int regionNumber; bool isTarget; bool isNotTarget; int probTarget; char objectName[128]; char objectClassName[128]; //オブジェクトだけの画像 IplImage *ObjImg; IplImage *ObjDepthImg; IplImage *ObjMaskImg; IplImage *ObjDepthMaskImg; //シーンの中での画像 IplImage *maskImg; IplImage *depthmaskImg; //オブジェクトの3次元点群 float *X_points; float *Y_points; float *Z_points; Vector3D center3D; Vector3D center3D_R_CORD; Vector3D volume3D; std::vector<int> color; std::vector<int> material; std::vector<float> material_likely; //std::map<int,float> material; std::map<int,float> shape_primitive; float roundness; int position[4]; //↑ ↓ → ← の順に 最寄りの物体の領域 番号 ないかも知れない void makeMask(IplImage*,IplImage*,int); void calcCenterPoint(IplImage*); void makeObjImg(IplImage*,IplImage*); ・・・・・ } [2] //extract 3d points std::vector<Vector3D> Points; Points.clear(); for(int y=0;y<this->ObjDepthMaskImg->height;y++){ for(int x=0;x<this->ObjDepthMaskImg->width;x++){ if(((uchar)this->ObjDepthMaskImg->imageData[this->ObjDepthMaskImg->widthStep * y + x]) > 0){ float X = this->X_points[ObjDepthImg->width * y + x]/100.0f; float Y = this->Y_points[ObjDepthImg->width * y + x]/100.0f; float Z = this->Z_points[ObjDepthImg->width * y + x]/100.0f; if( Z > 0 ){ Points.push_back(Vector3D(X,Y,Z)); } } } }

  • 開発環境:visual c++ 2008 windows

    開発環境:visual c++ 2008 windows vista ブロック崩しをつくっていまして、なんとかブロックを表示することができました。しかし、その位置がおかしいのです。 //////////////////////////////////////////////////////////////////////////////////////////////// // ブロック描画関数 //////////////////////////////////////////////////////////////////////////////////////////////// int Paint_Blocks(HDC hdc) { int i; if(blocks == 0) return 0; // ブロックが画面に1つも残っていなければ戻る HDC hdc_all; // デバイスコンテキストハンドルの定義 hdc_all = CreateCompatibleDC(hdc); // デバイスコンテキストハンドルの作成 SelectObject(hdc_all, hb_all); // オブジェクトの選択 for(i=0 ; i< block_count ; i++) { if(blocks[i].enable == 0) continue;      BitBlt(hdc,blocks-> x[i],blocks -> y[i], BLOCK_WIDTH, BLOCK_HEIGHT, hdc_all, 0, 5,  ←(2)    SRCCOPY);// 転送 } DeleteDC(hdc_all); // デバイスコンテキストの開放 DeleteObject(hdc_all); // オブジェクトの開放 return 0; } //////////////////////////////////////////////////////////////////////////////////////////////// // ゲーム初期化関数 //////////////////////////////////////////////////////////////////////////////////////////////// int Init_Game() { int i; // バー関連 bar.width = 30; bar.height = 5; bar.location.x = 100; bar.location.y = 210; // ボール関連【ブロック関連の初期化より先に書くこと】 ball.width = 4; ball.height = 4; ball.move = 1; ball.location.x = 80; ball.location.y = 180; // ブロック関連 block_count = 56; // ブロックの数 blocks = (blocks_info *)malloc(sizeof (blocks_info) * block_count); // ブロックの数分、メモリを確保する。 int k = 0; for(i=0 ; i < 4 ; i++) { int yy = i * (BLOCK_HEIGHT+3) + (ball.height * 2); for(int j = 0; j < 14; j++) {     blocks -> x[k] = j * ( BLOCK_WIDTH +3) + (ball.height * 2);          ←(1)       blocks ->y[k] = yy; blocks->enable = 1; k = k+1; } } return 0; } 自分の考えでは、矢印(1)で 変数j=0 のとき、配列x[0] は ball.height * 2 で 8 となり、 矢印(2)の bitblt関数で、x座標=8 から表示されると思っていました。 しかし、実際は ball.height などに100などの大幅な数字を代入してみても描写されるブロックの位置は全く変わりませんでした。 どうかアドバイスをよろしくお願いします。 

  • 合計値を求める関数

    #include<iostream> using namespace std; //sum関数の定義 int sum(int x, int y) { return x + y;  } int main() { int num1, num2, ans; cout << "1番目の整数を入力して下さい。\n"; cin >> num1; cout << "2番目の整数値を入力して下さい。\n"; cin >> num2; ans = sum(num1, num2); cout << "合計は" << ans << "です。\n"; return 0; }  ここのreturn x+y;の所の合計値を戻り値として返す処理の仕組みを解りやすく教えて欲しいです、戻り値はちょっと解りづらいです、よろしくお願いします。

  • Java 四角を書くツール

    Javaの初心者です。 下のプログラムで(2)のfを(1)のfに対応付けたいのですが、エラーが出てしまいます。 どなたか判る方いらっしゃいましたら教えてください。 import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.*; abstract class Figure { protected int x,y,width,height; protected Color color; public Figure(int x,int y,int w,int h,Color c) { this.x = x; this.y = y; width = w; height = h; color = c; } public void setSize(int w,int h) { width = w; height = h; } public void setLocation(int x,int y) { this.x = x; this.y = y; } abstract public void reshape(int x1,int y1,int x2,int y2); abstract public void paint(Graphics g); } class RectangleFigure extends Figure { public RectangleFigure(int x,int y,int w,int h,Color c) { super(x,y,w,h,c); } public void reshape(int x1,int y1,int x2,int y2) { int newx = Math.min(x1,x2); int newy = Math.min(y1,y2); int neww = Math.abs(x1 - x2); int newh = Math.abs(y1 - y2); setLocation(newx,newy); setSize(neww,newh); } public void paint(Graphics g) { g.setColor(color); g.drawRect(x,y,width,height); } } class DrawApplication { protected Vector<Figure> figures; protected Figure drawingFigure; static Color currentColor; protected DrawPanel drawPanel; public DrawApplication() { figures = new Vector<Figure>(); drawingFigure = null; currentColor = Color.blue; } public void setDrawPanel(DrawPanel c) { drawPanel = c; } public int getNumberOfFigures() { return figures.size(); } public Figure getFigure(int index) { return (Figure)figures.elementAt(index); } public void createFigure(int x,int y) { Figure f = new RectangleFigure(x,y,0,0,currentColor);                 // (1) figures.addElement(f); drawingFigure = f; drawPanel.repaint(); } public void reshapeFigure(int x1,int y1,int x2,int y2) { if (drawingFigure != null) { drawingFigure.reshape(x1,y1,x2,y2); drawPanel.repaint(); } } } class DrawPanel extends JPanel { protected DrawApplication drawApplication; public DrawPanel(DrawApplication app) { setBackground(Color.white); drawApplication = app; drawApplication.setDrawPanel(this); } public void paintComponent(Graphics g) { super.paintComponent(g); for(int i=0; i < drawApplication.getNumberOfFigures(); i++){ f = drawApplication.getFigure(i);           //(2) この部分にエラーが出てしまう f.paint(g); // } } } class DrawMouseListener implements MouseListener,MouseMotionListener { protected DrawApplication drawApplication; protected int dragStartX,dragStartY; public DrawMouseListener(DrawApplication a) { drawApplication = a; } public void mouseClicked(MouseEvent e) { } public void mousePressed(MouseEvent e) { dragStartX = e.getX(); dragStartY = e.getY(); drawApplication.createFigure(dragStartX,dragStartY); } public void mouseReleased(MouseEvent e) { drawApplication.reshapeFigure(dragStartX,dragStartY,e.getX(),e.getY()); } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseDragged(MouseEvent e) { drawApplication.reshapeFigure(dragStartX,dragStartY,e.getX(),e.getY()); } public void mouseMoved(MouseEvent e) { } } class DrawMain { public static void main(String argv[]) { JFrame f = new JFrame("Draw"); ButtonPanel b=new ButtonPanel(); DrawApplication app = new DrawApplication(); JPanel c = new DrawPanel(app); c.addMouseListener(new DrawMouseListener(app)); c.addMouseMotionListener(new DrawMouseListener(app)); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.getContentPane().add(c,BorderLayout.CENTER); f.setSize(400,300); f.setVisible(true); } }

    • ベストアンサー
    • Java
  • Swing実装での図形の追加と色の指定追加

    以下の作成した図形描写javaプログラムに図形の変更ボタン(円や直線)、色選択(例:赤、青、緑の三種)をおこなうことの出きるようにすればどうすれば良いでしょうか? import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.*; abstract class Figure { protected int x,y,width,height; protected Color color; public Figure(int x,int y,int w,int h,Color c) { this.x = x; this.y = y; width = w; height = h; color = c; } public void setSize(int w,int h) { width = w; height = h; } public void setLocation(int x,int y) { this.x = x; this.y = y; } abstract public void reshape(int x1,int y1,int x2,int y2); abstract public void paint(Graphics g); } class RectangleFigure extends Figure { public RectangleFigure(int x,int y,int w,int h,Color c) { super(x,y,w,h,c); } public void reshape(int x1,int y1,int x2,int y2) { int newx = Math.min(x1,x2); int newy = Math.min(y1,y2); int neww = Math.abs(x1 - x2); int newh = Math.abs(y1 - y2); setLocation(newx,newy); setSize(neww,newh); } public void paint(Graphics g) { g.setColor(color); g.drawRect(x,y,width,height); } } class DrawApplication { protected Vector<Figure> figures; /* Generics */ protected Figure drawingFigure; protected Color currentColor; protected DrawPanel drawPanel; public DrawApplication() { figures = new Vector<Figure>(); /* Generics */ drawingFigure = null; currentColor = Color.red; } public void setDrawPanel(DrawPanel c) { System.out.print("セットされました"); drawPanel = c; } public int getNumberOfFigures() { return figures.size(); } public Figure getFigure(int index) { return (Figure)figures.elementAt(index); } public void createFigure(int x,int y) { Figure f = new RectangleFigure(x,y,0,0,currentColor); figures.addElement(f); drawingFigure = f; drawPanel.repaint(); } public void reshapeFigure(int x1,int y1,int x2,int y2) { if (drawingFigure != null) { drawingFigure.reshape(x1,y1,x2,y2); drawPanel.repaint(); } } } class DrawPanel extends JPanel { protected DrawApplication drawApplication; public DrawPanel(DrawApplication app) { setBackground(Color.white); drawApplication = app; app.setDrawPanel(this); } public void paintComponent(Graphics g) { super.paintComponent(g); Figure f = new RectangleFigure(0,0,0,0,drawApplication.currentColor); for(int i=0;i<drawApplication.getNumberOfFigures();i++){ f = drawApplication.getFigure(i); f.paint(g); } } } class DrawMouseListener implements MouseListener,MouseMotionListener { protected DrawApplication drawApplication; protected int dragStartX,dragStartY; public DrawMouseListener(DrawApplication a) { drawApplication = a; } public void mouseClicked(MouseEvent e) { } public void mousePressed(MouseEvent e) { dragStartX = e.getX(); dragStartY = e.getY(); drawApplication.createFigure(dragStartX,dragStartY); } public void mouseReleased(MouseEvent e) { drawApplication.reshapeFigure(dragStartX,dragStartY,e.getX(),e.getY()); } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseDragged(MouseEvent e) { drawApplication.reshapeFigure(dragStartX,dragStartY,e.getX(),e.getY()); } public void mouseMoved(MouseEvent e) { } } class DrawMain { public static void main(String argv[]) { JFrame f = new JFrame("Draw"); DrawApplication app = new DrawApplication(); JPanel c =new DrawPanel(app); c.addMouseListener(new DrawMouseListener(app)); c.addMouseMotionListener(new DrawMouseListener(app)); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.getContentPane().add(c,BorderLayout.CENTER); f.setSize(400,300); f.setVisible(true); } }

  • 線の太さを変える コードのエラの意味が分かりません

     java勉強中の初心者です、宜しくお願いします。  下のようなコードを書きましたが、  >DrawPanel dp = new DrawPanel( X1 , Y1 , X2 , Y2 ) ;  >g2.setStroke( の二か所でエラーが出ています。 (エラーの内容はよく理解できません。) 一体どこが間違っているのでしょうか宜しくお願いします。 ================================================================= public class drawLine extends JApplet { int X1 = 20 , Y1 = 20 , X2 = 150 , Y2 = 150 ; public void init() { DrawPanel dp = new DrawPanel( X1 , Y1 , X2 , Y2 ) ; // dp.setSize( 30 , 200 ) ; // dp.setBackground( Color.cyan ) ; this.add( dp ) ; this.setBounds( 10 , 10 , 400 , 400 ) ; this.setBackground( Color.cyan ) ; this.setVisible( true ) ; } } //======================================================= class DrawPanel extends JPanel { Float currentWidth = 20.0f ; int x1 , y1 , x2 , y2 ; public DrawPanel( int x1 , int y1 , int x2 , int y2 ) { this.x1 = x1 ; this.y1 = y1 ; this.x2 = x2 ; this.y2 = y2 ; Graphics2D g2 = (Graphics2D)this.getGraphics() ; g2.setStroke ( new BasicStroke ( currentWidth , BasicStroke.CAP_ROUND , BasicStroke.JOIN_MITER ) ) ; g2.setColor( Color.red ) ; g2.drawLine( x1 , y1 , x2 , y2 ) ; } } ==============================================================================

  • 関数についての質問です。

    c言語を勉強しています。関数で戻り値がありますが、関数の処理の仕組みが理解できません。本等で勉強し僕の考え方が間違っていたら教えてください。 お願いいたします。 #include <stdio.h> int buy(int x,int y ) { int z; //1 printf("%d万円と%d万円の車を買いました。");//2 z=x+y; //3 return z; //4 } int main(void) { int num1,num2,num;//5 printf("いくらの車をかいますか?\n");//6 scanf("%d",&num1);//7 printf("いくらの車をかいますか?\n");//8 scanf("%d",&num2);//9 sum=buy(num1,num2);//10 printf("合計で%d万円です。\n",sum);//11 return 0;//12 } まず最初に 整数型、int num1,num2,numを読みます。 次に//7と//8で数値を入力します。 そして//10で値を格納し int buy( int x,int y)に値をわたします。 ※正確には関数buyに渡す。 そして計算をし計算結果 zをreturn で int buy(int x,int y )の buyに値を渡します。 そのあと呼び出し元の//10のbuyに値をかえします。 そしてプログラムが終了します。 間違っていたら教えてください。

  • Swing の実装でどうしてもエラーになります。

    初心者ですみませ。 次のリストがどうしてコンパイルを通っても実行時にエラーになってしまいます。どなたか、判る方原因を教えてください。 import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.*; abstract class Figure { protected int x,y,width,height; protected Color color; public Figure(int x,int y,int w,int h,Color c) { this.x = x; this.y = y; width = w; height = h; color = c; } public void setSize(int w,int h) { width = w; height = h; } public void setLocation(int x,int y) { this.x = x; this.y = y; } abstract public void reshape(int x1,int y1,int x2,int y2); abstract public void paint(Graphics g); } class RectangleFigure extends Figure { public RectangleFigure(int x,int y,int w,int h,Color c) { super(x,y,w,h,c); } public void reshape(int x1,int y1,int x2,int y2) { int newx = Math.min(x1,x2); int newy = Math.min(y1,y2); int neww = Math.abs(x1 - x2); int newh = Math.abs(y1 - y2); setLocation(newx,newy); setSize(neww,newh); } public void paint(Graphics g) { g.setColor(color); g.drawRect(x,y,width,height); } } class DrawApplication { protected Vector figures; protected Figure drawingFigure; protected Color currentColor; protected DrawPanel drawPanel; public DrawApplication() { figures = new Vector(); drawingFigure = null; currentColor = Color.red; } public void setDrawPanel(DrawPanel c) { drawPanel = c; } public int getNumberOfFigures() { return figures.size(); } public Figure getFigure(int index) { return (Figure)figures.elementAt(index); } public void createFigure(int x,int y) { Figure f = new RectangleFigure(x,y,0,0,currentColor); figures.addElement(f); drawingFigure = f; drawPanel.repaint(); } public void reshapeFigure(int x1,int y1,int x2,int y2) { if (drawingFigure != null) { drawingFigure.reshape(x1,y1,x2,y2); drawPanel.repaint(); } } } class DrawPanel extends JPanel { protected DrawApplication drawApplication; public DrawPanel(DrawApplication app) { setBackground(Color.white); drawApplication = app; } public void paintComponent(Graphics g) { super.paintComponent(g); // //[すべてのFigureをpaintする] // Figure f = new RectangleFigure(0,0,0,0,drawApplication.currentColor); for(int i=0;i<drawApplication.getNumberOfFigures();i++){ f = drawApplication.getFigure(i); f.paint(g); } } } class DrawMouseListener implements MouseListener,MouseMotionListener { protected DrawApplication drawApplication; protected int dragStartX,dragStartY; public DrawMouseListener(DrawApplication a) { drawApplication = a; } public void mouseClicked(MouseEvent e) { } public void mousePressed(MouseEvent e) { dragStartX = e.getX(); dragStartY = e.getY(); drawApplication.createFigure(dragStartX,dragStartY); } public void mouseReleased(MouseEvent e) { drawApplication.reshapeFigure(dragStartX,dragStartY,e.getX(),e.getY()); } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseDragged(MouseEvent e) { drawApplication.reshapeFigure(dragStartX,dragStartY,e.getX(),e.getY()); } public void mouseMoved(MouseEvent e) { } } class DrawMain { public static void main(String argv[]) { JFrame f = new JFrame("Draw"); // //[DrawApplicationとDrawPanelとDrawMouseListenerを作って組み立てる] // DrawApplication app = new DrawApplication(); JPanel c =new DrawPanel(app); c.addMouseListener(new DrawMouseListener(app)); c.addMouseMotionListener(new DrawMouseListener(app)); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.getContentPane().add(c,BorderLayout.CENTER); f.setSize(400,300); f.setVisible(true); } }

    • ベストアンサー
    • Java