Exemple #1
0
 public MonoBehaviour changeMotionModel(GlobalControl.motionModels newMotionModel)
 {
     //First, remove previous motion model
     DestroyImmediate (motionComponent);
     //Add the new motion model
     switch (newMotionModel){
         case GlobalControl.motionModels.DISCRETE:
             motionComponent = (MonoBehaviour)gameObject.AddComponent<MoveDiscrete>();
             break;
         case GlobalControl.motionModels.KINEMATIC:
             motionComponent = (MonoBehaviour)gameObject.AddComponent<MoveKinematic>();
             break;
         case GlobalControl.motionModels.DYNAMIC:
             motionComponent = (MonoBehaviour)gameObject.AddComponent<MoveDynamic>();
             break;
         case GlobalControl.motionModels.DIFFERENTIAL:
             motionComponent = (MonoBehaviour)gameObject.AddComponent<MoveDifferential>();
             break;
         case GlobalControl.motionModels.CAR:
             motionComponent = (MonoBehaviour)gameObject.AddComponent<MoveCar>();
             break;
     }
     motionModel = newMotionModel;
     return motionComponent;
 }
Exemple #2
0
 // Use this for initialization
 void OnEnable()
 {
     GlobalMove m = gameObject.GetComponent<GlobalMove> ();
     switch (m.motionModel){
     case GlobalControl.motionModels.DISCRETE:
         control = gameObject.GetComponent <MoveDiscrete>();
         controller = new PController(control);
         break;
     case GlobalControl.motionModels.KINEMATIC:
         control = gameObject.GetComponent <MoveKinematic>();
         controller = new PController(control);
         break;
     case GlobalControl.motionModels.DYNAMIC:
         control = gameObject.GetComponent <MoveDynamic>();
         controller = new PDController(control);
         break;
     case GlobalControl.motionModels.DIFFERENTIAL:
         control = gameObject.GetComponent <MoveDifferential>();
         controller = new PController(control);
         break;
     case GlobalControl.motionModels.CAR:
         control = gameObject.GetComponent <MoveCar>();
         controller = new PController(control);
         break;
     }
 }
    public EventCoroutine(string[] evs, MonoBehaviour owner = null)
    {
        events = evs;
        Owner = owner;

        CoroutineExecutor.Singleton.ProcessEvent += SendEvent;
    }
    public void SetButton(int index, MonoBehaviour script, string functionName)
    {
        if (index < 0 || index >= buttons.Length) return;

        buttons[index].onClick.Add(new EventDelegate(script, functionName));

    }
Exemple #5
0
 public override void Start(MonoBehaviour behaviour, Sequencer.StateInstance aState)
 {
     Entity ai = (Entity)behaviour;
     EntityMovement em = ai.entMove;
     em.Jump(speedMin < speedMax ? Random.Range(speedMin, speedMax) : speedMin);
     ai.state = state;
 }
Exemple #6
0
    public static void Pause(MonoBehaviour item)
    {
        if (item == null) return;
        item.enabled = false;

        Pauser.Pause(item.gameObject);
    }
    void ProcessMessage(MonoBehaviour behaviour)
    {
        bool AllOn  = true;
        bool AllOff = true;

        if (!Eneble){
            return;
        }
        for(int i = 0; i < TriggerButtonsOn.Length; i++){
            if(TriggerButtonsOn[i].State == c2StateButton.eButtonState.Off){
                AllOn = false;
            }
        }

        for(int i = 0; i < TriggerButtonsOff.Length; i++){
            if(TriggerButtonsOff[i].State == c2StateButton.eButtonState.On){
                AllOff = false;
            }
        }

        if(AllOn && AllOff){
            State = true;
            animation.CrossFade("Open");
        }
    }
Exemple #8
0
 void Awake()
 {
     Instance = this;
     Mono = this;
     mGlobalEvents = new List<IGlobalEvent>();
     DontDestroyOnLoad(this);
 }
	public static IEnumerator run_list(MonoBehaviour runner, IEnumerable<ActionWrapper> actions){
		foreach (ActionWrapper aw in actions) {
			Debug.Log("Running Coroutine");
			yield return runner.StartCoroutine(aw.run());
		}
		yield return null;
	}
Exemple #10
0
    public static IEnumerator publishScore(int level, int score,MonoBehaviour toPause)
    {
        yield return new WaitForEndOfFrame();
        try{
            if (!loged){
                CallFBLogin();
            }

            if (FB.IsLoggedIn)
            {

                var query = new Dictionary<string, string>();
                query["score"] = score.ToString();
                FB.API("/me/scores", Facebook.HttpMethod.POST, delegate(FBResult r) { FbDebug.Log("Result: " + r.Text); }, query);
            }
        }catch{
            PopUpMessage.ShowPopUp(Globals.texts.withoutConnection,Globals.texts.error,toPause);
        }

        /*if (FB.IsLoggedIn)
        {
            var querySmash = new Dictionary<string, string>();

            querySmash["ScoreByLevel"] = "http://samples.ogp.me/284034268417686";
            print(FB.AppId);

            FB.API ("/me/" + "orl.ag.orly" + ":smash", Facebook.HttpMethod.POST,
                    delegate(FBResult r) { FbDebug.Log("Result: " + r.Text); }, querySmash);
        }*/
    }
	private void displayInformationForUnit(IGameEntity entity) {

		//Remove previous values
		hideExtendedInformationPanel();
		    
		//Display window info
		windowInfo.GetComponent<Image>().enabled = true;

		currentPanel = Panel.UNIT;
		currentObject = (MonoBehaviour)entity;
		
		List<String> titles = new List<String>();
		titles.Add("Attack rate");
		titles.Add("Attack range");
		titles.Add("Movement rate");
		titles.Add("Resistance");
		titles.Add("Sight range");
		titles.Add("Strenght");
		titles.Add("Weapon Ability");
		List<String> values = new List<String>();
		values.Add(entity.info.unitAttributes.attackRate.ToString());
		values.Add(entity.info.unitAttributes.attackRange.ToString());
		values.Add(entity.info.unitAttributes.movementRate.ToString());
		values.Add(entity.info.unitAttributes.resistance.ToString());
		values.Add(entity.info.unitAttributes.sightRange.ToString());
		values.Add(entity.info.unitAttributes.strength.ToString());
		values.Add(entity.info.unitAttributes.weaponAbility.ToString());
		displayInformation(titles, values);
	}
Exemple #12
0
    public static void setSelected(GameObject obj)
    {
        if(objects[obj] == null)
            return;

        if(current_object == obj)
            return;

        current_file_loc = objects[obj].ToString();
        current_object = obj;

        string[] split_loc = current_file_loc.Split('/');
        string short_loc = split_loc[split_loc.Length - 1];

        string[] split_short_loc = short_loc.Split(':');

        string short_file_name = split_short_loc[0];
        string line_number = split_short_loc[1];

        current_line_number = Int32.Parse(line_number);

        string type_name = short_file_name.Split('.')[0];

        if(temp == null)
            temp = new GameObject("temp");

        temp.AddComponent(type_name);

        MonoBehaviour mb = temp.GetComponent(type_name) as MonoBehaviour;

        current_behaviour = mb;

        UnityEngine.Debug.Log(Fancy.current_behaviour);
    }
 public void PerformInjections(MonoBehaviour component)
 {
     foreach (IInjector injector in _injectors)
     {
         injector.PerformAllInjections(component);
     }
 }
Exemple #14
0
 public SimpleChat(string identifier,MonoBehaviour currentMonoBehaviour,string senderName)
     : base(identifier,currentMonoBehaviour,senderName)
 {
     continueCheckMessages();
     rt = -messageTime;
     setReceiveFunction(receive);
 }
    public static void SubscribeToEvent(EGameEvent _e, MonoBehaviour _subscriber)
    {
        Initialize();

        // assert _gameEvent >= GameEvent.EVT_GOAL_SCORED && _gameEvent < GameEvent.COUNT
        evtSubscribers [(int)_e].Add (_subscriber);
    }
Exemple #16
0
    public override void Start(MonoBehaviour behaviour, Sequencer.StateInstance state)
    {
        Entity ai = (Entity)behaviour;
        PlanetAttach pa = ai.planetAttach;
        AIState aiState = (AIState)state;

        float speed = speedMin < speedMax ? Random.Range(speedMin, speedMax) : speedMin;
        if(speed > 0) {
            if(followPlayer) {
                Player player = SceneLevel.instance.player;

                aiState.curPlanetDir = pa.GetDirTo(player.planetAttach, followPlayerHorizontal);
            }
            else if(!useDir) {
                aiState.curPlanetDir = Util.Vector2DRot(new Vector2(1, 0), angle*Mathf.Deg2Rad);
            }

            pa.velocity = aiState.curPlanetDir*speed;

            ai.action = Entity.Action.move;
        }
        else {
            pa.velocity = Vector2.zero;

            ai.action = Entity.Action.idle;
        }

        if(resetAccel) {
            pa.accel = Vector2.zero;
        }
    }
	void Start() {
		target = GetComponent(behaviour) as MonoBehaviour;
		if (!target) { 
			Debug.LogWarning("Did not find component " + behaviour + " on " + gameObject.name);
			Destroy(this);
		}
	}
    public override void Start(MonoBehaviour behaviour, Sequencer.StateInstance state)
    {
        Main.instance.cameraController.mode = mode;

        if(attachToPath.Length > 0) {
            GameObject go = ((SceneController)behaviour).SearchObject(attachToPath);
            if(go != null) {
                Main.instance.cameraController.attach = go.transform;
            }
            else {
                Debug.LogWarning("Path not found: "+attachToPath);
            }
        }
        else if(attachToWaypoint.Length > 0) {
            Transform t = WaypointManager.instance.GetWaypoint(attachToWaypoint);
            if(t != null) {
                Main.instance.cameraController.attach = t;
            }
            else {
                Debug.LogWarning("Can't find waypoint: "+attachToWaypoint);
            }
        }

        if(immediate) {
            Main.instance.cameraController.CancelMove();
        }
    }
    public BehaviorTree(string xmlPath, MonoBehaviour parent)
    {
        XmlReaderSettings settings = new XmlReaderSettings();
        settings.IgnoreComments = true;
        settings.ConformanceLevel = ConformanceLevel.Fragment;
        settings.ValidationType = ValidationType.None;

        this.parent = parent;

        using(XmlReader reader = XmlReader.Create(xmlPath, settings))
        {
            XDocument doc = XDocument.Load(reader);

            if (doc.Root.Name.ToString().ToLowerInvariant() != "behavior-tree")
                throw new XmlException("Behavior tree root node not found");

            if (doc.Root.Elements().Count() == 0)
                throw new XmlException("The behavior tree is empty!");

            if (doc.Root.Elements().Count() > 1)
                throw new XmlException("The behavior tree must have only one node at the top level");

            Dictionary<string, MethodInfo> leaves, conditions;

            LoadParentLeafFunctions(out leaves, out conditions);

            this.rootNode = ParseXmlElement(doc.Root.Elements().First(), leaves, conditions);
        }
    }
 public MapGenerator2(DungeonParameter param, MonoBehaviour obj,RndGenerator rnd)
 {
     DgParam = param;
     this.obj = obj;
     Rnd = rnd;
     reset();
 }
Exemple #21
0
 public void Callback(bool success,string response, List<RandomEvent> log, MonoBehaviour mb, string playId)
 {
     if(success)
     {
         mb.StartCoroutine(RegisterLog(log, playId));
     }
 }
Exemple #22
0
 public AIController(Tile.State owner, Board board, MonoBehaviour coroutiner, string scriptName)
     : base(owner, board)
 {
     prospector = new BoardProspector(owner);
     this.scriptName = scriptName;
     this.coroutiner = coroutiner;
 }
    void ProcessMessage(MonoBehaviour behaviour)
    {
        bool OpenCondition = true;
        bool NotYorButton = true;

        foreach (c2StateButton target in TriggerButtons){

            if (target == null) {continue;};

            if (target == behaviour){
                NotYorButton = false;
            }

            if (target.State != c2StateButton.eButtonState.On){
                OpenCondition = false;
                break;
            }

        }
        if (!NotYorButton){
            if (OpenCondition){
                animation.CrossFade("PullDown");

            }
            else{
                    animation.CrossFade("PullUp");
            }
        }
    }
    public override void Start(MonoBehaviour behaviour, Sequencer.StateInstance aState)
    {
        Entity ai = (Entity)behaviour;
        AIState aiState = (AIState)aState;

        ai.state = state;

        Vector2 src = ai.transform.position;
        Vector2 dest = Player.instance.transform.position;

        switch(type) {
        case Type.xOnly:
            dest.y = src.y;
            break;

        case Type.yOnly:
            dest.x = src.x;
            break;
        }

        Vector2 dir = dest - src;
        float dist = dir.magnitude;
        dir = dir/dist;

        float spd = minSpeed < maxSpeed ? Random.Range(minSpeed, maxSpeed) : minSpeed;
        ai.entMove.velocity = dir*spd;

        aiState.d = dist/spd;
    }
    // Returns whether or not the crop planting worked, if it works, it takes the cost from the players money
    public bool PlantCrop(string _uniqueId, MonoBehaviour tileToPlant)
    {
        Crop CropInfo = null;

        //Checks to see if tile is empty
        if (PlantedCrops.ContainsKey(tileToPlant))
        {
            return false;
        }

        //Gives CropInfo a Crop value
        for (int value = 0; value < AvailableCrops.Count; ++value)
        {
            if (AvailableCrops[value].UniqueId == _uniqueId)
            {
                CropInfo = AvailableCrops[value];
            }
        }

        //If no crop is present and player has enough money, plant crop and decrease money
        if (CropInfo != null && Money >= CropInfo.Cost)
        {
            PlantedCrops.Add(tileToPlant, new Crop(CropInfo));
            Money = Money - CropInfo.Cost;
            return true;
        }
        else
        {
            return false;
        }
    }
Exemple #26
0
 public void changeMotionModel(GlobalControl.motionModels newMotionModel)
 {
     //Destroy current motion model
     Destroy (control);
     //Add new motion model
     switch (newMotionModel){
         case GlobalControl.motionModels.DISCRETE:
             control = gameObject.AddComponent<MoveDiscrete>();
             controller = new PController(control);
             break;
         case GlobalControl.motionModels.KINEMATIC:
             control = gameObject.AddComponent<MoveKinematic>();
             controller = new PController(control);
             break;
         case GlobalControl.motionModels.DYNAMIC:
             control = gameObject.AddComponent<MoveDynamic>();
             controller = new PDController(control);
             break;
         case GlobalControl.motionModels.DIFFERENTIAL:
             control = gameObject.AddComponent<MoveDifferential>();
             controller = new PController(control);
             break;
         case GlobalControl.motionModels.CAR:
             control = gameObject.AddComponent<MoveCar>();
             controller = new PController(control);
             break;
         }
     motionModel = newMotionModel;
 }
Exemple #27
0
 public static YieldInstruction Start(CanvasGroup group, MonoBehaviour script, float from, float to, float time)
 {
     Stop(group, script);
     var coroutine = script.StartCoroutine(AnimateGroup(group, from, to, time));
     _fades.Add(group, coroutine);
     return coroutine;
 }
Exemple #28
0
 void Awake()
 {
     if (instance == null)
     {
         instance = this;
     }
 }
Exemple #29
0
 public static Task Login(MonoBehaviour owner, IPEndPoint endPoint, string id, string password, Action<string> progressReport)
 {
     var task = new UnitySlimTaskCompletionSource<bool>();
     task.Owner = owner;
     owner.StartCoroutine(LoginCoroutine(endPoint, id, password, task, progressReport));
     return task;
 }
    public void DispatchMessage(float delay, 	/*fa song zhe */int sender, 	/*jie shou zhe */int receiver, int msg,MonoBehaviour _be)
    {
        //jie shou zhe de zhi zhen
        BaseGameEntity pReceiver = EntityManager.Instance ().GetEntityFromID (receiver);

        //chuang jian yi ge xiao xi
        Telegram telegram = new Telegram (0, sender, receiver, msg,_be);

        if (delay <= 0.0f) {

            //li ji fa song xiao xi
            Discharge (pReceiver, telegram);
        } else {

            //yan chi fa song xiao xi
            float CurrentTime = Time.realtimeSinceStartup;

            telegram.DispatchTime = CurrentTime + delay;

            foreach(Telegram val in PriorityQ)
            {
                if(val.Sender == sender && val.Receiver == receiver && val.Msg ==msg)
                {
                    return ;
                }
            }

            PriorityQ.Add (telegram);

        }
    }
Exemple #31
0
 public void RemoveUpgrade(SquadBuilderUpgrade upgradeHolder)
 {
     Upgrades.Remove(upgradeHolder);
     MonoBehaviour.DestroyImmediate(upgradeHolder.Panel);
 }
Exemple #32
0
 public void HandleRewarded(object sender, Reward args)
 {
     MonoBehaviour.print("HandleRewarded event received: amout = " + args.amount + ", type = " + args.type);
 }
Exemple #33
0
    public void HandleImpression(object sender, ImpressionData impressionData)
    {
        var data = impressionData == null ? "null" : impressionData.rawData;

        MonoBehaviour.print("HandleImpression event received with data: " + data);
    }
 /// Use for registering with EventsManager
 public static void RegisterListener(this MonoBehaviour listener, GameEvent ev, Action <object> callback)
 {
     EventDispatcher.Instance.RegisterListener(ev, callback);
 }
Exemple #35
0
        private static void FindReferences(MonoBehaviour mono)
        {
            foreach (FieldInfo field in mono.GetType().GetFields()) //遍历T类的变量
            {
                object objValue  = field.GetValue(mono);
                Type   fieldType = field.FieldType;

                #region 自动找数组功能

                //如果是数组
                if (fieldType.IsArray)
                {
                    //判断是不是空的数组或者数组元素有填充了,就跳过
                    object[] objs = objValue as object[];
                    if (objs == null || objs.Length > 0)
                    {
                        continue;
                    }

                    //处理GameObject数组
                    Array filledArray;
                    Type  elementType = fieldType.GetElementType();
                    if (elementType == typeof(GameObject))
                    {
                        Transform[]  tfs     = mono.GetComponentsInChildren <Transform>();
                        Transform[]  tfHits  = Array.FindAll(tfs, item => item.name.StartsWith(field.Name, StringComparison.OrdinalIgnoreCase));
                        int          nLength = tfHits.Length;
                        GameObject[] gos     = new GameObject[nLength];
                        for (int i = 0; i < nLength; i++)
                        {
                            gos[i] = tfHits[i].gameObject;
                        }

                        filledArray = Array.CreateInstance(elementType, nLength);
                        Array.Copy(gos, filledArray, nLength);
                        field.SetValue(mono, filledArray);
                        continue;
                    }

                    Component[] coms    = mono.GetComponentsInChildren(elementType);
                    Component[] comHits = Array.FindAll(coms, item => item.name.StartsWith(field.Name, StringComparison.OrdinalIgnoreCase));
                    if (elementType != null)
                    {
                        filledArray = Array.CreateInstance(elementType, comHits.Length);
                        Array.Copy(comHits, filledArray, comHits.Length);
                        field.SetValue(mono, filledArray);
                    }

                    continue;
                }
                #endregion

                //因为UnityEngine.Object重写了空判断,所以要把objValue转成UnityEngine.Object再判断是否为空,
                if (objValue != null)
                {
                    Object uObject = objValue as Object;
                    if (uObject)
                    {
                        continue;
                    }
                }

                //查找自身的变量
                if (field.Name.Contains("Self"))
                {
                    if (fieldType == typeof(GameObject))
                    {
                        field.SetValue(mono, mono.gameObject);
                        continue;
                    }

                    Component com = mono.GetComponent(fieldType);
                    if (com)
                    {
                        field.SetValue(mono, com);
                        continue;
                    }
                }

                //迭代遍历子物体看看有没有同名的
                FieldInfo info = field;
                Transform tf   = mono.transform.FindChildRecursionExt(info.Name, StringComparison.OrdinalIgnoreCase);
                if (tf == null)
                {
                    continue;
                }

                //赋值操作
                if (fieldType == typeof(GameObject))
                {
                    field.SetValue(mono, tf.gameObject);
                }
                else
                {
                    field.SetValue(mono, tf.GetComponent(fieldType));
                }
            }
        }
Exemple #36
0
 public void HandleLeftApplication(object sender, EventArgs args)
 {
     MonoBehaviour.print("HandleLeftApplication event received");
 }
Exemple #37
0
 public void HandleRewardedAdFailedToLoad(object sender, AdFailureEventArgs args)
 {
     MonoBehaviour.print(
         "HandleRewardedAdFailedToLoad event received with message: " + args.Message);
 }
Exemple #38
0
    public void OnGUI()
    {
        if (ODCQCOODCC == null)
        {
            OQQOQODQDO = GUI.skin;
            ODCQCOODCC = (GUISkin)Resources.Load("ER3DSkin", typeof(GUISkin));
        }
        if (objectname == "")
        {
            objectname = GetNewRoadName();
        }


        GUILayout.Space(15);
        GUILayout.Box("", GUILayout.MinWidth(340), GUILayout.MaxWidth(340), GUILayout.Height(70));
        GUI.skin = OQQOQODQDO;
        GUILayout.BeginArea(new Rect(5, 5, 336, 250));
        GUILayout.Label("Set a name for the new EasyRoads3D Road Object");
        GUILayout.Space(65);
        GUILayout.BeginArea(new Rect(50, 40, 250, 150));


        RoadObjectScript.objectStrings    = new string[3];
        RoadObjectScript.objectStrings[0] = "Road Object"; RoadObjectScript.objectStrings[1] = "River Object"; RoadObjectScript.objectStrings[2] = "Procedural Mesh Object";



        EditorGUILayout.BeginHorizontal();
        GUILayout.Label("Object type", GUILayout.Width(75));
        objectType = EditorGUILayout.Popup(objectType, RoadObjectScript.objectStrings, EditorStyles.toolbarPopup, GUILayout.Width(150));
        EditorGUILayout.EndHorizontal();
        EditorGUILayout.BeginHorizontal();
        GUILayout.Label("Object name", GUILayout.Width(75));
        objectname = GUILayout.TextField(objectname, GUILayout.Width(150));
        EditorGUILayout.EndHorizontal();
        GUILayout.EndArea();
        EditorGUILayout.Space();
        EditorGUILayout.BeginHorizontal();
        GUILayout.Space(195);
        if (GUILayout.Button("Create Object", EditorStyles.toolbarButton, GUILayout.Width(125)))
        {
            if (objectname == "")
            {
                EditorUtility.DisplayDialog("Alert", "Please fill out a name for the new road object!", "Close");
            }
            else
            {
                bool     flag = false;
                string[] dirs = Directory.GetDirectories(Directory.GetCurrentDirectory() + backupFolder);
                foreach (string nm in dirs)
                {
                    string[] words = nm.Split('\\');
                    words = words[words.Length - 1].Split('/');
                    string nm1 = words[words.Length - 1];
                    if (nm1.ToUpper() == objectname.ToUpper())
                    {
                        EditorUtility.DisplayDialog("Alert", "An EasyRoads3D object with the name '" + objectname + "' already exists!\r\n\r\nPlease use an unique name!", "Close");
                        flag = true;
                        break;
                    }
                }
                if (!flag)
                {
                    GameObject go = (GameObject)MonoBehaviour.Instantiate(Resources.Load("EasyRoad3DObject", typeof(GameObject)));
                    instance.Close();
                    go.name = objectname;
                    go.transform.position = Vector3.zero;
                    RoadObjectScript script = go.GetComponent <RoadObjectScript>();
                    script.OOQDOOQQ      = false;
                    script.autoUpdate    = true;
                    script.surrounding   = 3.0f;
                    script.indent        = 3.0f;
                    script.geoResolution = 2.5f;
                    script.objectType    = objectType;
                    script.materialType  = 0;
                    if (objectType == 1)
                    {
                        script.objectText = "River";
                        script.forceY     = true;
                    }
                    if (objectType == 2)
                    {
                        script.geoResolution = 0.5f;
                    }
                    Selection.activeGameObject = go;
                }
            }
        }
        EditorGUILayout.EndHorizontal();
        GUILayout.EndArea();
    }
                public static void ToTerrain(this GameObject o)
                {
                    //// See if a valid object is selected
                    var obj = o;

                    if (obj == null)
                    {
                        return;
                    }
                    if (obj.GetComponent <MeshFilter> () == null)
                    {
                        return;
                    }
                    else if (obj.GetComponent <MeshFilter> ().sharedMesh == null)
                    {
                        return;
                    }

                    Vector3     size   = o.GetComponent <MeshFilter> ().mesh.bounds.size;
                    Vector3     center = size / 2;
                    TerrainData tData  = new TerrainData();

                    tData.heightmapResolution = 512;
                    tData.size = size;
                    GameObject oTerrain = Terrain.CreateTerrainGameObject(tData);
                    var        terrain  = oTerrain.GetComponent <Terrain> ();

                    var terrainData = terrain.terrainData;

                    terrainData.size           = size;
                    terrain.transform.position = -center;

#if UNITY_5
                    terrain.materialTemplate      = new Material(Shader.Find("Diffuse"));
                    terrain.materialTemplate.name = o.GetComponent <Renderer>().material.name;
                    terrain.materialTemplate.CopyPropertiesFromMaterial(o.GetComponent <Renderer>().material);
#endif

                    if (o.GetComponent <Renderer> ().material.mainTexture != null)
                    {
                        List <SplatPrototype> terrainTextureList = new List <SplatPrototype> ();
                        for (int i = 0; i < o.GetComponent <Renderer> ().materials.Length; i++)
                        {
                            SplatPrototype newSplat = new SplatPrototype();
                            Texture2D      texture  = (Texture2D)o.GetComponent <Renderer> ().materials[i].mainTexture;
                            newSplat.texture    = texture;
                            newSplat.tileSize   = new Vector2(size.x, size.z);
                            newSplat.tileOffset = Vector2.zero;
                            terrainTextureList.Add(newSplat);
                        }
                        terrainData.splatPrototypes = terrainTextureList.ToArray();
                    }

                    // If there's no mesh collider, add one (and then remove it later when done)
                    var addedCollider = false;
                    var addedMesh     = false;
                    var objCollider   = obj.GetComponent <Collider> () as MeshCollider;
                    if (objCollider == null)
                    {
                        objCollider   = obj.AddComponent <MeshCollider> ();
                        addedCollider = true;
                    }
                    else if (objCollider.sharedMesh == null)
                    {
                        objCollider.sharedMesh = obj.GetComponent <MeshFilter> ().sharedMesh;
                        addedMesh = true;
                    }

                    var resolutionX = terrainData.heightmapWidth;
                    var resolutionZ = terrainData.heightmapHeight;
                    var heights     = terrainData.GetHeights(0, 0, resolutionX, resolutionZ);

                    // Use bounds a bit smaller than the actual object; otherwise raycasting tends to miss at the edges
                    var objectBounds = objCollider.bounds;
                    var leftEdge     = objectBounds.center.x - objectBounds.extents.x + 0.001f;
                    var bottomEdge   = objectBounds.center.z - objectBounds.extents.z + 0.001f;
                    var stepX        = (objectBounds.size.x - 0.0019f) / resolutionX;
                    var stepZ        = (objectBounds.size.z - 0.0019f) / resolutionZ;

                    // Set up raycast vars
                    var        y = objectBounds.center.y + objectBounds.extents.y + 0.0001f;
                    RaycastHit hit;
                    Ray        ray          = new Ray(Vector3.zero, -Vector3.up);
                    var        rayDistance  = objectBounds.size.y + 0.0002f;
                    var        heightFactor = 1.0f / rayDistance;

                    // Do raycasting samples over the object to see what terrain heights should be
                    var z = bottomEdge;
                    for (int zCount = 0; zCount < resolutionZ; zCount++)
                    {
                        var x = leftEdge;
                        for (int xCount = 0; xCount < resolutionX; xCount++)
                        {
                            ray.origin = new Vector3(x, y, z);
                            if (objCollider.Raycast(ray, out hit, rayDistance))
                            {
                                heights[zCount, xCount] = 1.0f - (y - hit.point.y) * heightFactor;
                            }
                            else
                            {
                                heights[zCount, xCount] = 0.0f;
                            }
                            x += stepX;
                        }
                        z += stepZ;
                    }

                    terrainData.SetHeights(0, 0, heights);

                    if (addedMesh)
                    {
                        objCollider.sharedMesh = null;
                    }
                    if (addedCollider)
                    {
                        MonoBehaviour.DestroyImmediate(objCollider);
                    }

                    //if (obj.transform.parent) {
                    //    MonoBehaviour.DestroyImmediate (obj.transform.parent.gameObject);
                    //}
                    //else {
                    //    MonoBehaviour.DestroyImmediate (obj);
                    //}
                    MonoBehaviour.DestroyImmediate(obj);
                }
Exemple #40
0
 static void Start(MonoBehaviour behaviour, IEnumerator enumerable, Action action)
 {
     behaviour.StartCoroutine(StartImpl(enumerable, action));
 }
 /// Post event with param
 public static void FireEvent(this MonoBehaviour listener, GameEvent ev, object param = null)
 {
     EventDispatcher.Instance.FireEvent(ev, param);
 }
Exemple #42
0
 private void HandleRewardVideoLoaded(object sender, EventArgs e)
 {
     MonoBehaviour.print("rewardVideo loaded");
 }
Exemple #43
0
        public static void DOMove(this Transform transform, Vector3 startPosition, Vector3 endposition, float time = 1f, float delay = 0f)
        {
            MonoBehaviour script = transform.GetComponent <MonoBehaviour>();

            script.StartCoroutine(DOMoveCoroutine(transform, startPosition, endposition, time, delay));
        }
 /// Post event with no param (param = null)
 public static void RemoveListener(this MonoBehaviour sender, GameEvent ev)
 {
     EventDispatcher.Instance.FireEvent(ev);
 }
Exemple #45
0
 public override void Apply(MonoBehaviour behaviour, object obj, FieldInfo field)
 {
     ApplyInternal(behaviour, obj, field, null);
 }
Exemple #46
0
 /// <summary>
 /// Gets the text from URL.
 /// </summary>
 /// <param name="mono">Monobehavior</param>
 /// <param name="unityWebRequest">UnityWebRequest.</param>
 /// <param name="callback">Callback.</param>
 public static void GetTextFromPostRequest(this MonoBehaviour _mono, UnityWebRequest _unityWebRequest,
                                           Action <bool, string> _callback = null)
 {
     _mono.StartCoroutine(_mono.GetTextFromPostRequestCoroutine(_unityWebRequest, _callback));
 }
Exemple #47
0
 public override void Apply(MonoBehaviour behaviour, object obj, FieldInfo field, SearchStrategy searchStrategy)
 {
     ApplyInternal(behaviour, obj, field, searchStrategy);
 }
 public void ClearGrid()
 {
     MonoBehaviour.DestroyImmediate(gridObj);
     tileList = new List <Tile>();
     //for(int i=0; i<tileList.Count; i++) MonoBehaviour.DestroyImmediate(tileList[i].gameObject);
 }
 public void HandleRewardBasedVideoStarted(object sender, EventArgs args)
 {
     MonoBehaviour.print("HandleRewardBasedVideoStarted event received");
 }
Exemple #50
0
 public override void Initialize(MonoBehaviour actor, PlanDefinition planDefinition, IActionExecutionInfo[] actionExecutionInfos)
 {
     base.Initialize(actor, planDefinition, actionExecutionInfos);
     m_StateManager.Destroying += () => PlannerScheduler.CurrentJobHandle.Complete();
 }
Exemple #51
0
 public abstract void TouchDetected(MonoBehaviour thisObject, Collider2D otherObject);
Exemple #52
0
 /// <summary>
 /// Gets the text from URL.
 /// </summary>
 /// <param name="mono">Monobehavior</param>
 /// <param name="url">URL.</param>
 /// <param name="callback">Callback.</param>
 public static void GetTextFromURL(this MonoBehaviour _mono, string _url, Action <bool, string> _callback = null)
 {
     _mono.StartCoroutine(_mono.GetTextFromURLCoroutine(_url, _callback));
 }
Exemple #53
0
    public GameObject create(
        GameObject mod,
        Vector3 position      = default(Vector3),
        Vector3 rotation      = default(Vector3),
        bool fade             = false,
        GameObject father     = null,
        bool allParamsInWorld = true,
        Vector3 wantScale     = default(Vector3)
        )
    {
        Vector3 scale = mod.transform.localScale;

        if (wantScale != default(Vector3))
        {
            scale = wantScale;
        }
        GameObject return_value = (GameObject)MonoBehaviour.Instantiate(mod);

        if (position != default(Vector3))
        {
            return_value.transform.position = position;
        }
        else
        {
            return_value.transform.position = Vector3.zero;
        }
        if (rotation != default(Vector3))
        {
            return_value.transform.eulerAngles = rotation;
        }
        else
        {
            return_value.transform.eulerAngles = Vector3.zero;
        }
        if (father != null)
        {
            return_value.transform.SetParent(father.transform, false);
            return_value.layer = father.layer;
            if (allParamsInWorld == true)
            {
                return_value.transform.position    = position;
                return_value.transform.localScale  = scale;
                return_value.transform.eulerAngles = rotation;
            }
            else
            {
                return_value.transform.localPosition    = position;
                return_value.transform.localScale       = scale;
                return_value.transform.localEulerAngles = rotation;
            }
        }
        else
        {
            return_value.layer = 0;
        }
        Transform[] Transforms = return_value.GetComponentsInChildren <Transform>();
        foreach (Transform child in Transforms)
        {
            child.gameObject.layer = return_value.layer;
        }
        if (fade == true)
        {
            return_value.transform.localScale = Vector3.zero;
            iTween.ScaleToE(return_value, scale, 0.3f);
        }
        return(return_value);
    }
Exemple #54
0
 public static void FadeOff(CanvasGroup cg, float duration, MonoBehaviour owner, Action OnFadeOff = null)
 {
     owner.StartCoroutine(StaticFade(duration, false, cg, null, OnFadeOff));
 }
Exemple #55
0
 public static void FadeOn(CanvasGroup cg, float duration, MonoBehaviour owner, Action OnFadeOn = null)
 {
     owner.StartCoroutine(StaticFade(duration, true, cg, OnFadeOn, null));
 }
Exemple #56
0
 public Rotatable(MonoBehaviour source)
 {
     _source = source;
 }
Exemple #57
0
 public void HandleRewardedAdShown(object sender, EventArgs args)
 {
     MonoBehaviour.print("HandleRewardedAdShown event received");
 }
Exemple #58
0
 public void HandleRewardedAdDismissed(object sender, EventArgs args)
 {
     MonoBehaviour.print("HandleRewardedAdDismissed event received");
 }
Exemple #59
0
 public void HandleAdClicked(object sender, EventArgs args)
 {
     MonoBehaviour.print("HandleAdClicked event received");
 }
 public override bool IsAllowedEffect(MonoBehaviour effect)
 {
     return(((PlayHomeSettings)VR.Context.Settings).PostProcessingEffects &&
            (effect.GetType().Name.Equals("ImageEffectConfigChanger") ||
             (effect.GetType().Name.Equals("SSAOPro") && ((PlayHomeSettings)VR.Context.Settings).AllowSSAO)));
 }