CoRoutine type

Why to create a variable of Coroutine type. Can we use stopCoroutine with the name of that Coroutine so stop only one CoRoutine ?
Can we make the variable of serializedfield typ so we can swith it on and off ?
thanks for your efforts

Hi Kamel,

Can you post a copy/example of the code in question please.


See also;

Dear rob below is my code and the line I was suggesting is commented out nmber 68 if you past it in visual stuudio which is

Stop Coroutine (FireContinuously());

my query was can the local parameter Coroutine be a serializedField with true and false value ?1

using System;

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class Player : MonoBehaviour {

    // Configuration Parameter

    [SerializeField] float moveSpeed = 3f;

    [SerializeField] float padding = 1f;

    [SerializeField] GameObject projectile;

    [SerializeField] float laserSpeed = 10f;

    [SerializeField] float firingPeriod = 3f;

    //                           ++++++++++++++++++++++++++++++++++++++++++++++

    // Local Parameters

    float xMin, xMax,yMin,yMax;

    Coroutine firingCoRoutine ;

//___________________________________________________________________________________________________

	// Use this for initialization

	void Start () {

        SetUpMoveBoundaries();

	}

    

    //	                         ==============================================

    // Update is called once per frame

    void Update () {

        Move();

        Fire();

	}

   

    //                               ==============================================

    private void Move()

    {

        var deltaX = Input.GetAxis("Horizontal")* Time.deltaTime* moveSpeed;

        var newXPos =Mathf.Clamp(transform.position.x + deltaX,xMin,xMax);

        

        var deltaY = Input.GetAxis("Vertical") * Time.deltaTime * moveSpeed;

        var newYPos = Mathf.Clamp(transform.position.y + deltaY,xMin,xMax);

        transform.position = new Vector2(newXPos, newYPos);

    }

    //                               ==============================================

    private void SetUpMoveBoundaries()

    {

        Camera gameCamera = Camera.main;

        xMin = gameCamera.ViewportToWorldPoint(new Vector3(0, 0, 0)).x+(3*padding);

        xMax = gameCamera.ViewportToWorldPoint(new Vector3(1, 0, 0)).x-(3*padding);

        yMin = gameCamera.ViewportToWorldPoint(new Vector3(0, 0, 0)).y+padding;

        yMax = gameCamera.ViewportToWorldPoint(new Vector3(0, 1, 0)).y-padding;

    }

    //                               ==============================================

    private void Fire()

    {

        if (Input.GetButtonDown ("Fire1"))

        {

            /* Non Continuous Fire - remove CoRoutine

            GameObject laser = Instantiate(projectile, transform.position, Quaternion.identity) as GameObject;

            laser.GetComponent<Rigidbody2D>().velocity = new Vector2(0, laserSpeed);*/

            firingCoRoutine = StartCoroutine(FireContiuously());

        }

        if (Input.GetButtonUp("Fire1"))

        {

            StopCoroutine(firingCoRoutine);

            //StopCoroutine(FireContiuously();

        }

    }

    //                               ==============================================

    IEnumerator FireContiuously()

    {

        while (true)// for rpetitive firing

        {

            GameObject laser = Instantiate(projectile, transform.position, Quaternion.identity) as GameObject;

            laser.GetComponent<Rigidbody2D>().velocity = new Vector2(0, laserSpeed);

            yield return new WaitForSeconds(firingPeriod);

        }

        

    }

    //                               ==============================================

}

Hi Kamel,

You could pass in a string to be used as the name of the method to call in the coroutine, but, why would you want to?

The problems that are associated with this are quite big, it’s bad enough using a string with with the coroutine in the first place in code, e.g. StartCoroutine("MyMethod"); because if you ever rename that method Visual Studio is never going to know that its referenced in those quotation marks - but at least - as a programmer - you would have been looking in the code.

If you now move that method name out of the code into the Inspector you are allowing someone to type in anything, the StartCoroutine method will try to call the name of the method which could very well not exist and you’ll get an error and your game will fail.

You might be able to expose a list of methods using reflection and custom editor script(s), that way you would be able to provide the designer with a list of methods in the Inspector that actually exist but I would argue that this would be hugely over-engineering something for a reason I suspect does not require/deserve that amount of time.

You mentioned in your reply about passing in a bool, would this be because you want the ability to turn on/off rapid fire, e.g. have it as a feature? Assuming so, rather than exposing the method name for the firing, I would just have a bool (which you can use [SerializeField] with) for rapid fire. Then, in your code, add some logic which, based on that bool will either start the coroutine, or not. In the check used to determine whether to call StopCoroutine, you would just add the additional bool in that validation also, e.g. if we are in rapid fire mode and we are firing, stop firing.

Hope this helps. :slight_smile:

Thanks for the explanation, it is clear enough for me why not to use a string . One more thing if you allow me not relevant

I could not use Random.Range in visual studio 2017 the editor would compile the file so I had to use fixed value. Moreover the [SerializedField ] type wouldn’t appear from the editor choicesdespite being out of the scope of any method ??!!!.

Thanks again

1 Like

Hi Kamel,

I could not use Random.Range in visual studio 2017

Without seeing the error, or a screenshot it is a bit hard to tell, but I would imagine it is due to the namespace clash. Both .Net and Unity have a class called Random which contains a method named Range. You sometimes have to be explicit with the namespace, e.g UnityEngine.Random.Range(min, max).

Moreover the [SerializedField ] type wouldn’t appear from the editor choicesdespite being out of the scope of any method ?

Do you mean that when you started to type, the Intellisense within VisualStudio didn’t offer it as a suggestion, like this screenshot;

image

Spot on adding specifying the source of the method corrected the fRandom.Range issue and the second exactly as you describe it.

Thanks for your help

1 Like

You’re very welcome :slight_smile:

Thanks for prompt reply. The Random.Range issue is solved by adding Game Unity. beforehand. The querry about the serialized field is as you described it , the dropdown menu doesn’t include it !

Hi Kamel,

The querry about the serialized field is as you described it , the dropdown menu doesn’t include it !

How are you opening the scripts? e.g. what are the steps you take? and which versions of Unity and Visual Studio are you using?

I open visual studio 2017 through unity 2018.1f

Ok, good.

Some things to check and try;

Within Visual Studio, on the right hand side (typically), you will see the Solution Explorer. If you look within that you should see a folder level called References.

This is where all of the imported libraries are shown, expand it and have a look through to confirm UnityEngine is definitely in that list.

Assuming so…

Right-click on your solution and then choose Clean Solution, you will see some output to the console within Visual Studio, it should report success when it’s finished.

Next, right-click on your solution and choose Build Solution, again you should see output to the console which will report success.

Close Visual Studio.

Switch back to Unity and double-click one of your script files to launch Visual Studio, this will also open the solution/project(s).

Try adding the [SerializeField] attribute again, does the intelligence appear now?

Thanks much apprecciated

Is it working now Kamel?

It is not consistent but I used to manage it by removing the script, save the game, close it and relaunch it which did exactly what you suggested it but in over-engineered way.

One more favour please if you have time, in block breaker when the ball reaches high speed from bouncing it disappears, how can I solve that ?

1 Like

It’s typically best to keep questions to one topic each, this helps with readability, however you could try;

  • reducing how fast the ball can travel
  • making sure that the relevant Rigidbody components have Collection Detection set to Continuous or Continuous Dynamic

Hope this helps :slight_smile:


See also;

Privacy & Terms