Programming」カテゴリーアーカイブ

プログラミング全般に関するカテゴリーです。

Collider2D.IsTouchingが常にfalseになってしまう場合

詳細はよく分かりませんが、静止状態でない場合にCollider2D.IsTouchingが正しく判定されないことがあるみたいです。

[Unity] collider.IsTouching(collider) が動いてる状態だとまともに動かない件。バグ?|Unity|エンジニアリングメモ
http://chusotudensi.blog.shinobi.jp/unity/-unity-%20collider.istouchin

ということで、そういう場合はBounds.Intersectsあたりを使って接触判定するなどのworkaroundが使えるみたいです。

if (_Collider.bounds.Intersects(_Collider2.bounds))
{
  Debug.Log("Bounds intersecting");
}

Collider2D.IsTouchingで困っている人は試してみてください。

リンク

Unity – Scripting API: Collider2D.IsTouching
https://docs.unity3d.com/ScriptReference/Collider2D.IsTouching.html

Unity – Scripting API: Collider2D.bounds
https://docs.unity3d.com/ScriptReference/Collider2D-bounds.html

Unity – Scripting API: Bounds.Intersects
https://docs.unity3d.com/ScriptReference/Bounds.Intersects.html

C#でグローバルな定数を扱いたい時

C#でグローバルな定数を扱いたい時、いろいろな方法があると思いますが、static classusing staticを使うという方法があります。

使い方は次のような感じです。

定数の定義

static class Value
{
  public const int size = 10;
}

定数の使い方

using System;
using static Value;

class Example
{
  static public void Main ()
  {
    Console.WriteLine($"size = {size}");
  }
}

using staticを使うとクラス名.の部分が省略でき、見やすくなるので便利です。

リンク

using static directive – C# Reference | Microsoft Docs
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-static

UnityのWebGLゲームを外部からJavaScriptで操作する方法

UnityでビルドしたWebGLのゲームを外部からJavaScriptで操作したい場合、unityInstanceSendMessageを使うと実装できるみたいです。注)

実装の仕方

WebGLでビルドするとindex.htmlというファイルが作られると思いますので、<body>から</body>の間のどこかに

<input type="button" value="ボタン" onclick="…">

のような感じでコードを追加します。

このonclickの部分でunityInstance.SendMessageを実行すればWebGLのゲームにメッセージを送ることができるみたいです。

ExampleオブジェクトのFunctionメソッドを呼び出したい場合

unityInstance.SendMessage('Example', 'Function');

ExampleオブジェクトのFunctionメソッドにvalueを引数として渡して呼び出したい場合

unityInstance.SendMessage('Example', 'Function', value);

※メッセージを送るトリガーとしてボタンを使う必要はありませんので、その辺りは適当に読み替えてください。

リンク

Unity – Manual: WebGL: Interacting with browser scripting
https://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html


注) 古いドキュメントではgameInstanceとなっている場合もありますが、Unity 2019.1以降はunityInstanceに変更されたそうです。