2

I was wondering if I could assign multiple variables to one object without having to assign it to a variable then assign them. So for example is it possible to convert this:

GameObject obj = Pooler.Instantiate().GetComponent<Asteroid>();
obj.speed = speed;
obj.direction = -1;

To look something like this:

Pooler.Instantiate().GetComponent<Asteroid>().({speed = speed, direction = -1});

When I do that, I get an error, so I was wondering if it was possible to do something like that?

1
  • 1
    You can use that syntax as part of object initialization, for example new Asteroid {speed = 0, direction = 1}, but only then. Seems like it's not possible in your case. Commented Feb 14, 2015 at 17:57

1 Answer 1

4

"Assigning multiple variables at once" would be called object initializers in C#. Here is a classic example:

Old way:

   Person person = new Person();
   person.FirstName = "Scott";
   person.LastName = "Guthrie";
   person.Age = 32; 

New way:

var person = new Person { FirstName="Scott", LastName="Guthrie", Age=32 };

Both syntaxes include the keyword "new".

Sign up to request clarification or add additional context in comments.

1 Comment

@TheBoogieMan yes, that's correct, this is called object initializer syntax.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.