#💻┃code-beginner
1 messages · Page 659 of 1
Alpha cutoff is usually 0.5. But I don't understand why your cutout area is different to the alpha you're providing. Unless you've done something weird in the importer settings
hmm none of that should be changed
and deleting and reimporting a new version of the texture ends up as expected
bleeds like that if i turn alpha is transparency on
ohwell for texting purposes it should still work
!docs
where should I go to learn C#
I tend to think this is pretty good: https://learn.microsoft.com/en-us/collections/yz26f8y64n7k07
for unity..?
Unity uses standard C#.
learning C# will help you with Unity
You either want to put in the effort or you don't ¯_(ツ)_/¯
That is true. I am just afriad I won't remember all of this.
It's a skill like any other. It takes practice
Alright.
It's the simplest code but I'm getting something wrong: it's supposed to be that when the player activates the button, the door opens, and when the player enters the door's collider, they're teleported to a transform.position that I put somewhere in the scene
The door opens just fine, but the player is completely ignored when they try and pass through. Could I get some help? :[
Do you see the logs indicating that the position setting line is called?
I don't recieve either of the debug logs for the collision, only debugs I get are the door being set to open, and the button being pressed :[
Share !code correctly next time.
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
So you don't see "the player can't enter the door right now"?
Nope 
Sure! The only messages I seem to get are the two first debug logs
The whole console please.
Make it a habit to show people the whole context. Don't cut screenshots in the middle.
Weirdly enough if I switch off the 'is Trigger' for the box collider, I get all of the debugs but it still fails to teleport the player
Oh okay! Sorry about that :[
Anyways, the fact that the collision is not triggered, means that either there are missing colliders(on a door or the character), or a missing rigidbody(on one of them), or one/both are marked as triggers, or they don't physically collide.
Yes, triggers generally trigger OnTriggerEnter. Not "Collision".
Because they're triggers obviously.
So, since has passed through the door is printed, it means that the position is set. However, what is it set to? Debug the name of the object you set position for.
These values are serialized and set in the inspector, don't use GetComponent and re-assign them to something else, and especially don't assign the player and door to the same transform this component is attached to
Im completely new to unity/programming and I cant find how to make my 2D character freeze in place. Its for an Aerial Attack, to make the character freeze in place so he dont fall and/or stops rising. or if any1 here knows how to?
where can I find info or a template?
Also every object with GetComponent has a .transform method so you never need to use GetComponent<Transform>(), just use .transform
using UnityEngine;
using UnityEngine.InputSystem;
public class FollowShip : MonoBehaviour
{ public Transform player;
[SerializeField] private float MousePosY;
[SerializeField]private float MousePosX;
[SerializeField] private float LimitRotationX;
[SerializeField] private float LimitRotationY;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
MousePosY = Input.mousePosition.y;
MousePosX = Input.mousePosition.x;
player.rotation = Quaternion.Euler(-MousePosY,-MousePosX,0);
}
}
``` can i make the rotation movement smooth, or just any tips to make my code better
It depends on how you're moving the object in the first place. To make stop moving just don't move it.
Maybe look up some tutorials. There's barely any code to comment on.
you dont have to remember everything, pretty much everything is documented nowadays
just make sure to practice your logic skills and to not copy code you dont understand
you can use Lerp
I just installed Google Sign plugin in to my unity project and got all these errors. Any idea how to fix it?
The screenshot is unreadable
They're errors with unity packages. Remove/ readd/ update them.
is it possible to inspect the value of a GameObject's private attributes at runtime? I'd like to look through a Dictionary to make sure the values have been set correctly
yes.. but if you mean via inspector no for dictionaries by default
non-serialized fields in general, you can use debug mode, but iirc they still have to be serializable, which dictionaries aren't
ah
you could use the SerializedDictionary plugin, but for something like this i would probably just log it out manually to check
that works very differently from Godot (where you can inspect any attribute at runtime and also change the value of any attribute at runtime) :P
in general you can use [SerializeField] with a private or protected accessor
except when the attribute is not serializable, got it
things being public make it serliazable implicitly, which lets it be viewed in the inspector as a by product
(access modifier?)
"accessor" is an umbrella term for getters and setters, for properties in the case of c#
my b
and yeah if you do wanna use dictionaries in the future i can +1 ayellowpaper's asset on the asset store, it's free, works fine and is used in the exact same way
a declaration consists primarily of a type and a name, any other keywords you add are "modifiers"
e.g., ref/out for parameters, const/readonly for fields, static,abstract,sealed, override, virtual, etc, and of course, public/protected/private/internal
they can be divided into groups by usage, and the latter 4 are "access modifiers"
ok this is more of a c# question: when I inherit the class containing this ToString override, the inheriting class contains a public new string name which overrides the value of name (right?).. but calling that class's ToString uses the value of name from the original class instead of the override value
it doesn't override name, it just shadows it
it creates a new name of the current class instead of using the inherited name
is there any way to make ToString reference the new name in subclasses, without having to duplicate the code to each one?
(btw, string interpolation would probably make this more readable at a glance, that might be what the suggestion on String there is saying)
why does the subclass have a new name to begin with?
this Action class represents an action that can be taken in my game, so it's inherited by classes that implement specific behaviour
-# uh so there's already a c# class called Action. the overlap isn't an issue in itself but that might get confusing fyi
so, why would each subclass have its own name field in your setup?
-# like actually, what's its current purpose
when the player makes an ambiguous action, I want to be able to prompt them with a UI element listing the options they can take
so every action type needs a readable name
ok, and why isn't that using the existing field
do you set the name in the inspector or something
wdym by this?
what's the purpose of the new name field?
ok hold on
Action already has a name field you could use to specify names. what purpose does the new name field serve?
Why not just reuse the existing name field from the base class?
let me show my code and maybe that will help explain my intention
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
public class Action
{
public string name = "GenericAction";
public Piece piece;
public Vector2Int tile;
public Action(Piece _piece, Vector2Int _tile)
{
piece = _piece;
tile = _tile;
}
public override string ToString()
{
return String.Format("{0}: ({1}) -> {2}", name, piece, tile);
}
public virtual void Execute(Board board) {}
}
public class Move : Action
{
public new string name = "Move";
public Move(Piece _piece, Vector2Int _tile) : base(_piece, _tile) {}
public override void Execute(Board board)
{
board.MovePiece(piece, tile);
}
}
public class Score : Action
{
public new string name = "Score";
public Score(Piece _piece, Vector2Int _tile) : base(_piece, _tile) {}
public override void Execute(Board board)
{
board.ScorePiece(piece);
}
}
a pastebin would be preferred, but sure
yeah so, the new name isn't exactly adding anything
well, it's adding a new separate field
I see
instead of using the existing name field that Action knows about
you would use the Action's name field to set names
to be 100% clear incase your unaware, you can access values declared in classes your inheriting (assuming the access modifier isn't private)
Please never ever ever ever use the new keyword, get rid of that immediately
you could either set the name directly in the constructor of each subclass, or you could specify another constructor overload which accepts a name
or internal
Use the proper convention, make it virtual and override name
You could use a Name property and override it in the sub sclasses.
or protected etc. ye
(no i mean if it's internal or private then you can't access from a subclass)
can you give an example of this declaration? e.g. replacing line 6 here
internal should work?
you can do that with fields?
No, so it should be a property
ah
internal is namespace scope, no?
Assembly
internal means you have to be in the same assembly
if it's a subclass in the same assembly, it can access
if it's a subclass in a different assembly, it can't
You could argue file is namespace scope, but this is specifically scoped to files
There's no such thing as namespace scope
private protected just means it's private to a class, but derived classes can also access it within the same assembly
that would be protected
like this?
public virtual string name { get; set; } = "GenericAction";
you wouldn't need a setter, would you?
petitioning parole as a new namespace scoped modifier 😛
could be name => "GenericAction"
No need for a setter
Unless you want to mutate this
Well yeah it's technically just a method string Get_Name() in this case
so subclasses should pretty much duplicate this line, just replacing virtual with override, correct?
Correct
Also if you type override, followed by a space, VS should inform you of what can be overridden, and the name should be in that list.
Whatever the case, never use new. It's behaviour is not what you expect if you end up using it for overriding behaviour in derived classes
In your case an attribute would be an even better approach, but this requires more code (and considering in your case it's purely logging likely also a pointless addition which brings more complexity)
-# well, maybe except for extending MonoBehaviour lol
instansiating scriptableobjects at runtime go brrr
BTW considering the name is always the class name, why not just log the class name?
String.Format("{0}: ({1}) -> {2}", this.GetType().Name, piece, tile);
Unless your logs are intended to show a more detailed name in the future, in which case it doesn't apply
btw @alpine summit
fair
one more question, I'm struggling to override Equals so that it checks whether the other object is the same subclass of Action
You can just do if (obj is Action)
This is a pattern match against a type, and will work if obj is Move for example
There are other approaches, but this is the most simple check in Unity
Alternatively, use var action = obj as Action to do a safe explicit cast. If the type was not implementing Action, the variable will be null
If you do if (obj is Action), you can follow it with var action = (Action)obj to cast it. Note this should be checked beforehand, or it will throw an exception
I believe modern Unity even supports if (obj is Action action), meaning you immediately assign to the variable on the same line. This is the best way to do this
right, but will this compare, for example, a Move : Action object against a Score : Action object? I want these to evaluate as not equal, even if their attributes have the same values
Then compare GetType() of Move against GetType() of Score
The Type type in C# will properly compare against its own type.
General question about input that is probably preference anyways, is it “better” to add to the movement once per update and then clear when handled (fixed update for example) or set every update. I can see upsides and downsides for both
Ideally if you intend to override equality in a specific custom way, consider using IComparer<T> and create a comparer specific to this.
The thing is that this is now the default. If you happen to want proper reference equality (or equality by strictly comparing piece/tile) then you no longer have this. If you then also make an IComparer<T> for comparing piece/tile you have the maximum amount of control.
(By default class comparison is by reference so this would not need one)
Input in Update()
Movement in FixedUpdate() -> don't want movement to change because of fps (higher fps == more Updates, lower == less)
But do you set it each time or add to the value then reset?
You generally don't move and reset the value after moving.. unless you want it to now stop moving
var verticalSpeed = Vector3.Dot(currentVelocity, motor.CharacterUp);
if (_requestedSustainedJump && verticalSpeed > 0f)
effectiveGravity *= jumpSustainGravity;
currentVelocity += motor.CharacterUp * effectiveGravity * deltaTime;```got any ideas how to smooth out the reduced gravity when you trigger `_requestedSustainedJump` and afterwards?
I'm thinking of a lerp but not too sure how to implement it
Do you have a URL for the unity docs explaining every piece of code
like for example where it'll show what instantiate does etc
!docs
Are there any free ways to work on a project with multiple people, and have a way to store assets?
not really a code question, but use version control like git or unity version control
Where could I host it though?
Github
A full game won't fit there
Mine does
It offers 1gb iirc
you recall incorrectly
2d?
I couldn't even push an empty project there
You didn't set up the git ignore correctly then
probably because you are trying to push your library folder which includes files over 100mb which are beyond the single file limit (which is what git LFS is for), but that folder should be ingored anyway
Will it even work without it?
It does work without it
what? without LFS? sure as long as you don't have files over 100mb
Without a library folder
the library folder is automatically generated by the editor
If you do it on GitHub then you can just choose "Unity" in the gitignore list
I'm kind of confused to why my array is clearing out all of the elements in an array set in the inspector after I start the game. They return after I stop the game. Why is this happening? The arrays hold a custom class.
Because you have code clearing those arrays
I currently only got 2 classes and I don't see any line of code that could do something like that.
Here's the code: https://pastebin.com/1zsMAadJ
https://pastebin.com/crU2NFrJ
Hi friends I have one project in which I am drawing shapes and need to compare them to shapes on the scene if they are the same that shape will destroy, I am thinking about linerenderer but how can it be possible to compare two shapes because the second is drawn randomly by the player?
Change those arrays from public to [SerializeField] private so you can still set them in the inspector but not have them changed by another script
that didn't fix the problem unfortunately. What could possibly cause this issue that aren't my classes.
a linerenderer is just a way to render a line. have you looked up any way to do this? this isnt going to be some simple comparison between points.
Do the objects you have dragged in to the inspector still exist when you hit play
I thought I can compare the linerenderer point and check if it's nearly similar or not but other then that I have no idea
yeah. Every single "Heart" is the holder of the "HeartState" class. They do not disappear on runtime.
you can
but as soon as the user draws something slightly too large or small, or angled incorrectly, the algorithm breaks. this would fall under like "shape matching" or "shape recognition" if you wanted to look up algorithms. not something ive coded myself but theres definitely more to consider than just the points
Can you show a full Unity screenshot, before and after hitting play, with the object with the arrays selected and visible in the inspector, and your hierarchy expanded like this one? Just so I can check a whole bunch of stuff at once and avoid a bunch of back-and-forth
Yes, I have played this game i am definitely sure it's not using points comparison in that
How can I compare shapes?
Let me understand this, you're trying to compare a player drawn shape to an image?
you look up algorithms to do this.
Sure.
Maybe I can convert them to texture and then compare them if they are nearly the same or not
Is there anything in the console after you hit play?
No. Literally nothing.
Are you sure you don't have errors hidden?
Don't got much knowledge about the type of arrays there're in unity but if I'm not wrong there's multiple. Like dictionaries, lists and stuff like that. Perhaps I should use another type of array or something?
no literally no errors no comments no warnings
I wonder if it's the [System.Serializable] on the HeartState? MonoBehaviours are already serializable, maybe adding this tag is making Unity try to serialize them twice and loading the wrong one?
No, I actually removed that minutes ago. Thought that could be the case as well
Inside the Start method of the HeartState, add this log:
Debug.Log($"{gameObject.name} HeartState initialized.");
Run it and count how many times that appears
I don't know how is it in unity but could it be because I didn't do something like "using HeartState;"? In unreal engine that's at least something you need to do.
HeartState is not a namespace
sorry, #include. If that's even a thing in C#
Nope that is not it. Just checked
Man this is so much different from the other engine I used for a while.
It logged 10 times.
I doubt that'll give us anything though. It's not a constructor after all
unless I don't understand what was the intent of doing that
I wanted to eliminate the possibility that they were getting destroyed and re-created, therefore losing the references
How about this: Comment out the array variables and the entire body of the DamageHeart function (keep the actual function header so it'll still compile), then run the game. See if anything gives an error then
If you straight up remove the variables, whatever was modifying them will now be throwing an error
Yeah I have no idea what happened there
must've been the engine's error or something
I commented out the arrays, compiled and then uncommented them and assigned all the classes to where they need to be and on runtime everything is fine now
I do tend to forget stopping the game before making changes and so perhaps the changes persisted after I stopped the game and made the engine confused?
Maybe that serialized attribute caused them to fail to save properly, and removing the attribute wasn't enough? Commenting them out would force the serializer to remove those values from the scene object, so when they got added back in they were properly serialized?
When you exit play mode, everything reloads from disk so it would be at the last place the scene was before you hit play mode. Changes to the hierarchy and scene objects during play mode aren't saved to disk
perhaps just restarting the engine could've also solved the issue. In any case it's solved now
What's the best way again for me to paste a script in here so i can double check my work? It's just a copy/paste playermovement that i want to make sure is working with my player capsule so i can have a movable character
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
But if you want to see if it's working just... try it?
Oh, woops, wrong command
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I don't know why I did IDE, I think I need more caffeine
Well that's why I'm here cause it's definitely not working lol. When I push play there's nothing going on but I can see my capsule. I'm certain I'm probably missing some steps so I'm watching some videos on how to make characters
Or make moving characters rather
So to start with, post the code
So I got the camera on the player and the camera can rotate but doesn't move with WASD
Show the inspector of this object
Where is the script
In the link I provided
No, on the object
Well if your issue is that the player isn't moving on the X or Z axes, I think this is probably a good place to look
Well that's what the guy showed in his video lmao but let me try and see if that does it
You might want to check again and make sure you're looking at the right object
Maybe he just showed freeze rotation and just wasn't paying attention SMH
Low and behold
Or however you say it. That did it lol
Moves slow though so gotta adjust that but thank you
what is the best practice for showing the user a UI window and waiting for them to click a button before continuing? Specifically w.r.t. the code for waiting, since I've already made a boolean flag that I can toggle to make the game stop accepting input while the UI is visible
relevant code
Create a public function, perhaps called "inputClicked()", in your Game script that you can attach to the OnClick event for the Button.
for sure
but how do I pause this function's execution until the button is clicked?
by which I mean the function in the image
bool waitingForInput = true;
void Update() {
if (!waitingForInput) {
acceptInput = true;
}
}
this won't work for my use case, since I still need to run more code after the button is clicked
you either use update or a coroutine. either works in your case. id probably start with a coroutine since it seems simpler in this case
Is this a horrible way to handle abilities? I'm trying to learn how and when to use Coroutines right now. Also, I ran into an error here when the "cooldown" in the Boost method was shorter than the duration, I thought the code would stop the coroutine if it's called before it's started again
you would yield until receiving the input
Coroutines can be re-run multiple times at the same time. If you only ever want one running then you want to store an IEnumerator variable that points to the one currently being run, and you can stop that before running another
Oh I see now, so it's stopped before it removes the existing speed modifier, is that right
in this case, what happens at the place where this function was called from? Will it also pause execution until the input is recieved?
I'll try this, thanks
yea thats a pretty bad way. more so because it's all hardcoded strings and values. If it suits your use case then 🤷♂️ it works
I honestly hate coroutines, so I would use Update().
float timeUntilBoostExpires = 0f;
float boostTime = 3f;
// ...
// add boost
timeUntilBoostExpires = boostTime;
// ...
void Update() {
updateBoost();
}
void updateBoost() {
if (timeUntilBoostExpires > 0) {
timeUntilBoostExpires -= Time.deltaTime;
}
if (timeUntilBoostExpires <= 0) {
// removeBoost.
}
}
so a better way would be to store the values in a scriptable object?
I don't have a use case, I just want to learn how to use coroutines and how to write better code
you can probably use an enum for this
Scriptable Object is better for a number of reasons, like being able to swap abilities in and out of entities that use them
They can't run coroutines, but no reason why you can't have a monobehaviour run it for them, as long as the MB does not get destroyed during that lifetime.
when you yield, the coroutine will resume later like next frame. The method that called the coroutine doesn't get affected
oh I see
the method that called the coroutine doesn't get affected as in, it will resume execution immediately upon calling the coroutine?
also one more question (sorry, I've used godot in the past and I'm new to unity): I'm a bit confused on how I can make a button press cause the coroutine to continue
a method that calls a coroutine never "pauses" in the first place. It calls StartCoroutine, the coroutine runs until it hits a yield, the method that called it will finish its logic
So you want something to wait until you push a button?
correct
You could add a while() loop to the coroutine, waiting for a bool to become true.
many ways, you can yield until something is true. you can just keep yield returning null unless a bool is true
https://docs.unity3d.com/ScriptReference/WaitUntil.html
Task completion sources are good for this when using async (Awaitable or UniTask)
Whether its an update, coroutine, async, or something else, the simplest way is that the button press just executes a simple method that flips a boolean to true.
The waiting method needs to check each frame if the boolean is true, and if so, exit that loop it's in
while (waitBool == false) { yield return null; } for example if its a coroutine
bawsi's advice also works just as well
Contrivance's sample code is 10x better than the sh*t on that docs page bawsi linked.
does a coroutine always have a return type of IEnumerator? can a coroutine take any arguments?
I just had a look at that code link, and it's a bit odd because it uses a lambda, which is going to confuse some people who have never used one before
exactly
I'm more familiar with lambdas than coroutines 😂
🤷♂️ people possibly being confused by basic c# doesn't make it shit.
that's a limitation of coroutines. Returning values back is tricky and requires some workarounds with actions.
An alternative is to look into async, or grab UniTask, which is a free code package that uses async. But UniTask will make more sense if you get some experience with coroutines or async on your own.
I'll try async
It's not complicated in the slightest either way. Nothing about it is shit. It's really just preference in what people want to use.
I really wouldnt lol
If you dont understand coroutines, you really aren't gonna succeed with async
And you don't need it here either
Coroutines also have one flaw in that yield always waits a frame, so if you have multiple chains of yields you will lose a lot of frames. The game's framerate will still be fine, that's unaffected, but the control and flow might feel stuttery or slow
what's basic is using a while() loop, like what we were saying, and your link doesn't have that word anywhere in it. instead, it forces the user to learn one or two new things, if not more.
that's why most documentation online is trash
I see
I would also suggest trying Update() first. If that doesn't make sense, then branch out into coroutine/async
"not making sense" meaning it doesn't fit your use case
if you dont understand lambda thats fine. The person actually asking the question said they did anyways. You don't need a while loop here and "your link doesn't have that word anywhere in it" ok? I'm not here religiously defending using WaitUntil. Like i said, it's preference for what people would want to use in the moment
they said they knew lambda after the fact
Welcome to Unity, we are very opinionated 😄
putting this in the Update loop feels a bit spaghetti, but the use case is simple enough that it should work
Unitask completion source
it would still be nice to learn about some other options :P
I still do think a coroutine simplifies your use case compared to update. This really is 2 lines that you'd need to add
can you paste the code you're trying to change?
Also this is code-beginner. Nothing wrong with coroutines when you're first starting out.
private bool TryAction(Piece piece, Vector2Int tile)
{
List<Action> actions = LegalActions(piece, tile);
// check for valid action
if (actions.Count == 0)
{
return false;
}
else if (actions.Count == 1)
{
actions.First().Execute(this);
}
else
{
acceptInput = false;
// TODO: show ui
// await button press here
acceptInput = true;
actions[actionToExecute].Execute(this);
}
return true;
}
public void OnActionChoiceButtonPressed(int choice)
{
actionToExecute = choice;
}
Boardgame essentially?
ideally the function that calls TryAction would also wait for the button press
Using coroutines to enforce the turn-based nature of a boardgame makes sense to me. Its how I first started with making a turn based dungeon crawler.
You'll find you need to make a lot of your game with coroutines, since most things will wait for other things to process
The good news is that if you build it all with coroutines, and then find you prefer async/UniTask, it's not a huge refactor to change over. Everything will still use the same flow of methods you had before, you're just changing the method signatures and how they're being called. A day's worth of work. So definitely go with coroutines at first
note: show ui is still todo because I need generate buttons for each item in actions. But it should be easy to do this in code and link them to OnActionChoiceButtonPressed
hopefully it's possible to bind an argument to the buttons' function call like it is in godot
I guess I can use a lambda for this
it is
what logic does the function that calls TryAction need to do? It might be easier if the coroutine calls a function afterwards and just passes it a value
when a piece is released over a tile, I call TryAction and do some more logic afterwards depending on the bool return value
OnLMBUp is called from AcceptInput which is called from Update. I'm sure you can infer the rest
it definitely does get a little awkward here because it's not setup in a way to allow coroutines. I think the simplest thing would be just moving the code that runs after TryAction(...) to also happen from the coroutine
then inside TryAction you wouldnt need to return. You would also want to ideally set actionToExecute to -1 for example, then yield while its -1
is this good practice? It feels a bit weird because if I hit the tile == NoHover branch here then I need to run the code after the if/else immediately
that logic could likely just move up into the if statement then. I wouldnt really call it bad practice because the alternative would mean you also make OnLUMBUP a coroutine. Yet returning the value would still be a problem.
ok sure, that makes sense
you would also want to move that validAction logic purely to the coroutine because I don't think it'd be used here otherwise
yeah so here's what I have now
TryAction has a void return value now, but it still takes arguments
and now I just need to make it a coroutine that waits for the button press
you can still pass parameters. the only thing now would be changing the return to IEnumerator, calling StartCoroutine() and yielding based on a condition
im not sure how you have it setup, but just incase youd want to make it isnt possible to start many coroutines here. Possibly AcceptInput or OnLMBUp shouldnt run when they're already trying an action
also just to make sure I understand the control flow correctly, a coroutine returns upon hitting a yield, and continues execution later when... something happens?
I guess the only thing I'm not clear on is how to define what the "something" is
it's on the same line as the yield, right?
when it hits a yield it doesn't execute more code, it will come back and resume when the yielding code actually yields
It's whatever the yield returns. By default, yield return null means "Next frame" but you could also yied return new WaitForSeconds(3f) to continue 3 seconds later for example
So if you are yielding on a startcoroutine, it will wait there for that coroutine to finish
I see
if you yield return null that just means you wait one frame before continuing. if you use something like WaitUntil, you define a condition that must evaluate to true before it continues. Coroutines check every frame if it should continue
or yield return new WaitUntil(SomeBoolFunction) which will wait until that function returns true
ahh
The rest of your project will continue to run as normal, it just pauses that particular method for later
ok so it works how I thought
how can I make the coroutine return like a normal function?
as an example, you can replicate a yield return new WaitForSeconds(x) by doing something like this:
float timer = 0f;
while (timer < 3)
{
yield return null;
timer += Time.detaTime;
}
there is definitely some wrong code here
You cannot return without yielding in an IEnumerator. If you want to end early, it's yield break
And WaitUntil takes a function that returns a boolean, not a boolean
Are you using System.Collections?
that fixed it, thanks
Anyone knows how to set up Discord Presence timer? I made the connection but the time in the activity stays at 00:00, I
don't know how to edit the startTime from code
{
Debug.Log($"Friend Count: {client.GetRelationships().Count()}");
Activity activity = new Activity();
activity.SetType(ActivityTypes.Playing);
activity.SetDetails("Exploring the Mansion");
activity.SetState("Playing Solo");
client.UpdateRichPresence(activity, (ClientResult result) => {
if (result.Successful())
{
Debug.Log("Rich presence updated!");
}
else
{
Debug.LogError("Failed to update rich presence");
}
});
}```
@eternal needle @brave robin @polar acorn got things working, thanks for the help! 
wait... why is the for loop variable passed by reference? D:
that's just how it is
Congratulations, you've stumbled upon the most miserable annoying fiddly piece of programming esoterica that I will always fall for every time: "Lambda Capture".
The variable i is actually not in the for loops scope, it's defined outside of the scope and accessible within it. It's essentialy like having int i = 0 before the loop.
This means that by the time the delegate is run, that variable has changed, and the scope that contains it still exists, so it uses the latest value of it.
The solution, as completely pointless as it sounds, is to add
int j = i;
as the first line of your for loop and use j in your delegate
I was just about to ask whether this would work
thanks
the i is actually in the for's scope though
it's just the same i throughout each iteration, hence why i++ works
right, i is in scope of every loop iteration as opposed to a single one
makes sense
So I'm messing around with spell casting using gestures, and I've got my code working so that I can click and drag within an image on a UI Canvas to draw a shape. Then my comparison function compares the shape drawn against a predefined shape pattern. Done.
But now, I want the player to be able to right-click to activate drawing the shape anywhere and right-click again to end drawing the shape. But my brain is melting thinking of the Game Dev way of making that work for both mouse and Gamepad Stick. Can someone help guide me in the right direction?
Right now my code to check for the mouse position is
RectTransformUtility.ScreenPointToLocalPointInRectangle(playerGestureArea, Input.mousePosition, uiCanvas.renderMode == RenderMode.ScreenSpaceOverlay ? null : uiCanvas.worldCamera, out localPoint);
Should I have like...an invisible UI element in front of the player camera at all times while the wand is equipped? Waiting to be used as a canvas for the gesture?
It's kind of a middle context, it doesn't apply outside the for loop, but it's the same variable in each iteration of the loop
oh i see what you're trying to say
While defining something in the body of the loop means it's a variable unique to that iteration of the loop
yeah no it is in the for's scope, just not the for's body's scope
it's declared within the for statement, rather than the block of its body
Right, it's an incredibly unintuitive thing that basically every Functional Programming language has to deal with
and I step on that rake every goddamn time
I have at least hit it in Java, C#, Python, and Haskell
c++ and java handle this pretty well imo
in java, anything you use in a lambda has to be final or effectively final (meaning it's never reassigned to)
in c++, you have to be explicit about what you capture by value or reference
you can't hit it in java, java doesn't let you
(but yeah i agree on the rest of what you said)
Hello everyone! I'm trying to make to blue car's behaviour less jank (forcing him NOT to jump out of the road right after he respawns) and i tried clamping his spawn angle to 270 (paralel to the road), reducing his turning speed, doing whatever i can to make him behave less crazy, but nothing has quite worked.
Here is the code if you'd like to look at it:https://paste.mod.gg/lefrsinbvvve/0
If you're wondering, yes the blue car does want to hit the yellow car.
A tool for sharing your source code with the world!
Just to clarify a bit, I think what I'm not really understanding in my head is "how do I create points on a 2D plane when my character is being controlled in a 3D space"
Raycast maybe?
uh about the camera jitter, maybe you could constrain x rotation and y position to stop the jittering
(though, kind of a band aid fix that closes off some options in the future)
Then grab the transforms and drawline between those points.
Just checking, is that in response to me, or Nilo?
projecting points onto the plane, perhaps?
Thank you very much! I don't think the car will have to go up a hill or anything it should be fine.
or maybe you would have a canvas in screenspace for that instead of world space
You. Best way to get a position is raycast. You can have it happen every 0.5 seconds and then draw line between those points for the visual portion.
Might need to fiddle with the values of a Vector3 to get the correct positions etc.
Fortunately I don't need to draw any lines between points. I just need a plane on which points can be placed, but one that's "static" in that it doesn't move in relation to the player's position in 3D space.
This
So next question then, when a Player is moving the mouse to change the aim of their character in a 3D game where the mouse isn't visible, is the "Input.mousePosition" also changing with that?
I had assumed that the mouse was "locked" in a position, but its input was being interpreted into the player looking around.
You won't be able to draw the shape AND control the character at the same time.
I wouldn't be able to turn the character, no. But they could still walk around
Right?
Yes.
well, keyboard and mouse input are separate, so that's up to your design choices
If you use the mouse to look and WASD or arrows to move then you can accomplish that easily.
Just a bool check to see if the mouse click is down or up, or drawing is active etc.
I do. Yeah. That part I'm not too worried about. When the player is casting, I'm actually going to limit how quickly their character looks around, so there's some natural movement of their head if they move their mouse around, but much more limited than when they aren't casting.
You could time dilate too. Slow the game when drawing or something.
But the element I'm still kinda confused about is The UI Canvas in Screen Space. Do I understand right that Screen Space is...the screen? Like, the Canvas is "anchored" to the screen?
It is anchored to the screen. Add a canvas and in the camera option just set it to "screen space"
yeah, screenspace is a 2d plane matching the screen
the canvas renders directly onto the camera, without consideration for position or rotation as something in world-space would require
So then if I'm understanding right, though, there's the potential that the starting position of the player's mouse (because they've been playing in 3D space this entire time) is off in a corner somewhere. Right? I bet there's a way to reset that.
Super useful for HUD etc.
It only uses x and y. And always returns within 0 and your resolution set (1920 x 1080) etc.
When a canvas is drawn in Screen Space, is it possible to make the Canvas LARGER than the screen?
you don't draw a canvas in screenspace, you set it to be in screenspace
you can't control its size directly
No but you can move things outside the canvas
maybe nested canvases could be set like that but... what's the point?
So if you want something offscreen, you can just put it outside the bounds of the canvas
I know that sounds unintuitive, but the thing I'm stuck up on is that in a 3D game, the player wouldn't know where their mouse was. And maybe I'm getting caught up too much on the "mouse" element of it. But let's say the player rotates their character 360 degrees to the left using the mouse. My understanding is that their mouseposition would be on the left side of the screen.
If they wanted to draw an image (which they can't see) starting from that spot, there wouldn't be any way to draw to the left.
isn't there a method to set the mouse position though
I think that's one piece of it, but the other is if the player made a big, exaggerated motion to cast their spell, it's possible their mouse could get stuck at the top or bottom, or sides of the screen. And so the gesture they draw would be cut off.
you could also just use mouseDelta so you don't have to care about the initial position at all
(not sure if that would solve the screen edge issue though)
If i clamp the X rotation the car wont move...
Peculiar
the x rotation specifically?
rb.constraints = RigidbodyConstraints.FreezeRotationX; right?
why not just set the constraints in the inspector though
ah.
yeah so that assignment means it only locks the one you specified, you would have to do or assignment
but just setting it in the inspector would be much easier
If i have an (2d) array of structs that har say color information, and wanted to display that information as ‘pixel art’, how would i update texture to have that information?
I did freeze the X rotation, the car did not move once again :|
which is weird because i don't think it would depend on that?
so perhaps the ground just isn't level?
Nope, the car is running on roads which are just objects, 0, 0, 0 rotation.
https://paste.mod.gg/bhvmdlywsbqt/0 if you'd like to take a look at my code
A tool for sharing your source code with the world!
but i am pretty sure the car should move either way.
it does without the ground
It only shakes like crazy when the yellow car hits any object or goes in the sidewalk though...
call it a feature?
it's slightly nauseating so probably not lmao
maybe a little camera smoothing could make it stay a feature
Clamp the camera rotation?
anyways about your actual question i think you should start by debugging it to see what it's trying to do
not what i'm referring to, no
How could i do that? Slowly check what its doing frame by frame?
sure, yeah
quick question, the freeze position Y should keep any object on the same height right?
Because the blue car still goes down if there ins't a road underneath him
yeah
Awnsering this, i think because the blue car respawns infront of the yellow car, and the blue car wants to hit the yellow car, it turns as hard as it can despite being infront of the yellow car.
So what i could do is make the blue car NOT turn when in front of the player
check the z displacement, i guess?
no, the difference of z position between the blue car and the yellow car
gameObject.transform.position = target.transform.position + new Vector3(-20f, 0f, 0f);
This should make it so it spawns directly infront the yellow car right?
oh you're driving in -X?
then yeah
is that the problem?
so change this to x displacement
i mean, if your code assumes the road goes in +Z, then it could be
I'm not sure if it does
but then again the only time it touches the z axis is when respawning the blue car.
and matching it with the players
gameObject.transform.position = target.transform.position + new Vector3(-20f, 0f, 0f);
right here
well doesn't look like it
really?
wdym z angle?
i mean z axis, my apolagies
nothing in your code touches that either
this is the x axis
yes, so the blue car spawns in front of the player. by touching i mean making it so it copies the other positons
including the z axis
ah
Not one frame after the blue car respawned
I was correct, the blue car tries turning as hard as it can into the player.
This is because its probably trying to turn around like this: 🔄 to try and hit the player but it cant because of the angle limiting
I went frame by frame and i could see the blue turning to the left right after respawning
wait, your rigidbody is dynamic, right?
in that case, the rigidbody controls the transform. you shouldn't modify the transform yourself
ah okok.
but i think i got a fix to this actually
i made it so the blue car only turns when it is close enough to the player (-5f, can change it alittle bit)
yeah but modifying the transform is still gonna be an issue
also i don't think that's a very good fix
unless it's already heading towards the player, it's never gonna turn towards the player
if i let it have a little breathing room it might, right?
if it was turning at -20f, and i let it turn at -5f, it could work
also how would the transform be an issue?
not a very good assumption
rigidbody controls the transform
you control the transform
you fight for control with the rigidbody
tell the rigidbody to move the transform instead
the rigidbody has methods for that
also for the initial transform.position =
rb.transform.position = target.transform.position + new Vector3(-20f, 0f, 0f); like this?
so swapping out gameObject for rb?
Im making a 2d game, does anyone know how to add a main menu where you can open tabs like settings and start the game?
right click below where your gameobjects are -> UI -> panel, from there you can add stuff
watch a tutorial on it
whenever i try to add a button ui, i dont see it in the game view
I wish i could help you mate but i can't. I mostly work on 3d and im new to this whole shabang.
Check some tutorials, practice a bit.
oh nw
@hexed hare https://learn.unity.com/tutorial/working-with-ui-in-unity# have a read of this to learn UGUI
In this tutorial, you will learn: Teach how to put Anchor buttons to sides and adjust their width and height Teach how to put Anchor UI Text to the top-center of the Canvas and adjust the screen width How to use the anchor presets to lock UI elements to corners and sides of the UI menus Teach how to use the Canvas Scaler to automatically adjust...
Is it on a canvas
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Why is this giving me an error? When I do "Vector2.right" it doesn't give me any error even though it's equivalent to the same thing
that's not equivalent to the same thing. you're trying to call the Vector2 constructor here which requires the new keyword. Vector2.right is a static property, not a constructor
Is there any tutorial you can suggest me? I already went through one but because I am trying to learn fast I am going through mutliple stuff at the same time = me forgetting them
Because that's not how you create an instance of something
there are beginner c# courses pinned in this channel
I'm already going through one
I am just talking about vectors
this isn't an issue of not understanding vectors, this is an issue of not understanding constructors and properties, both of which are basic c# concepts
This isn't something unique to vectors, you would use new any time you're creating an instance of something
transform.Translate(new Vector2(1,0) * Time.deltaTime); or transform.Translate((new Vector2(1,0)) * Time.deltaTime);
is going unity pathways the same as the tutorials provided?
i would personally recommend learning the basics of c# first and separately from unity. it will be easier to grasp the relevant concepts as you won't be learning two things at the same time so you'll be able to focus on learning the language then you'll have an easier time learning the engine since you'll have a better understanding of how the language works.
I recommend doing microsoft's c# course then doing the pathways on the learn site
Now that I know some basics of coding, does anyone have a 2d game idea they recommend me?
a simple one, but not too simple?
anything top-down would be simple.
pong, flappy bird, doodle jump, simple things like that. this is also not a code question.
where wuld i ask it?
Do a platformer game where you may occasionally fight enemies, platformer going sideways not upwards
Wdym top down?
try to add some puzzles
so terraria?
bird's eye view.
terraria would be more difficult because you have to worry about gravity, platforms, jumping through platforms, etc.
up to you 😄 I just came up with the idea
Btw this was what I was doing at the beginning (through code academy) 😭 but they asked what me what's the point of that 😭
who is "they"? because "they" sound potentially uninformed
someone here
!docs
I would suggest starting with w3schools C# course: https://www.w3schools.com/cs/index.php - its completely free and their lessons are more like sandbox puzzles to practice what you learn, when you become familiar with that, you could try to challenge yourself by combining multiple lessons to make something specific or try the Unity Learn tutorials if youd rather dive right into games
{
progressBar.fillAmount = Mathf.Clamp01(timer / timerInterval);
}```
trying to use the fill amount value for an image but its not working
What isn't working about it?
And what debugging steps have you taken?
no dont worry its cause the image was set to none
so wasn't given me an option for image type
apologies if im being dense here but currently the cannonball that is the projectile is being shot upwards how can i change it too fire in the direction that the cannon is pointing
no, that's the same thing
do rb.position = ...
as for the turning, you can use torque or angular velocity
your upwards velocity is 700 but your other directions are 1 so it's gonna look like it's straight up
it looks like a one time thing here, so you should be using an Impulse type force instead (and probably could just be AddForce
okie i was following the unity lauch projectiles guide thing to make a cannon but i am kinda struggling
then you would incorporate the transform direction into the AddForce; the force is in world-space
What would be the best way to color code my texts?? Like do I make a scripts that holds a reference of all the colors I wanna use, do I pass the text over some kind of method that automatically does the color changes or do I do it manually??
In the past i've had a <List<string>,Color> dict that's used in a static function that colour codes all the text i send it
eg. in inspector
Sounds like I should REALLY not be iterating a script in search of specific words if I am also going to keep updating it somewhat frequently right??
i mean at some point your gonna have to iterate somewhere
depends more on where your storing the words
I mean "string" sry
I mean, I can do it manually, just that it can leave to a lot of typos and it's very tiresome to do
you could use a dictionary for ~O(1)
either a bit less flexible or a bit less friendly than what batby showed above perhaps
stuff like this being automatic is good for iteration efficiency and later down the line accessibility reasons
either a dict of strings to colors (the latter option) or a dict of strings to enums with enums to colors defined separately (the former option)
only reason why mine wasn't a dict was lack of serialized asset usage at the time of making it iirc
Also, not sure I can use that, although sounds very usefull
you can't make it a dict, no
at least, not in that format
I want numbers to also show color coded, numbers that I have no idea of what they are gonna be lol
oh boy, regex
what do you mean by that
https://paste.mod.gg/tljgyodigous/0
full code for how this was used btw
A tool for sharing your source code with the world!
something like this 123 maybe
you could also have a function to colorize them that you use when interpolating directly
I mean this is kinda of the format I want to have, ignoring that I have no idea of how to make icons like that lol
i mean moreso that what makes the number a given colour
It would be helpful, but I assumed it would take a while
How would I even do that?
Stuff scales with a given stat, stats should have an associated color to be more readable
usage: $"Some text {NumberFormat(numberValue)} more text"
definition: string NumberFormat(int val) => $"<color=#FFC000>{val}</color>"
or could be something like definition: string CritChanceFormat(float val) => $"<color=#FF0000>{val*100:F0}% Crit Chance</color>"
that color could be defined per "stat" or depending on how this text is being composed you could use the color you get from the related word
eg. with something like this you could have a function like
public static Color GetFormattedColor(string word)
and could extend that further with
public static string FormatValue(int value, string refText)
where you could use it like
Debug.Log("Magic Damage = " + ColorLibrary.FormatValue(mgDmg, "magic"))
or implement a function that colors the entire string based on the first or most occurring coloured word found where it might look like
Debug.Log(ColorLibrary.ForceColor("Magic Damage = " + mgDmg))
and maybe with an extension so just
Debug.Log(("Magic Damage = " + mgDmg).ForceHighlight())
so then the library find the word magic, sees you've associated it with blue and returns that entire string blue
Uh, that seems.... pretty complex?? And I am not sure I want to be calling stuff like that every like half a second that I need to be refreshing the UI
you know you shouldn't be refreshing your UI every half a second
if you wanna keep doing that there's inherit limitations in how you can/should engineer your UI
I update it ever 30 frames, if the UI is showing and if there is something to show in there
I don't think I can go much lower than that
Yeah, that would be: whenever damage is dealt or healed, whenever a buff/debuff happens or ends, whenever they spend any resource, whenever their logic changes or the player interacts....
As I said, it happens too often for a event based system to be a meaningfull improvement
Like they may have 3 change value over time effects ticking at different frames intervals and that would already be more than each 30 frames
I mean it depends on the game but in a majority of genres each of those mechanics would happen significantly less often than every half a second (based on a 60fps limit)
you could possibly cache these results at runtime
What I am trying to do is sorta of a complex semi-autobattler where you give "suggestions" on what you want your guys to be doing on sorta of a raid-like enviroment
Yes, I need a lot of updates of that type
A single big target may have like 20 effects on it a time
something like this would be pretty easy to cache because you could just store the input and output in a dict
if its an input you've recieved before, just hand out the output
if its not, do the work and save the input and output for later use
I do all of this sort of stuff using custom formatters in Localization
It's definitely one of the more complicated things to get working though, definitely not #💻┃code-beginner material
yeah my suggestion is pretty bare bones and far from a magic bullet
Yeah, I don't plan on doing any localization lol, I think Imma just gonna try adding icons and set the color of the numbers manually, which is a total chore, but oh, well
an idea for icons is to make a custom font and put them as symbols you're not gonna need
You should just use <sprite>
I was about to use that, yeah
i thought about this too, if youre planning on comercializing your game localization is one of the strongest points
its a pain in the ass but yea
not sure where to ask this but i was trying to add image to a button and it wont let me do it.... i converted the image to sprite and it doesnt show up in the sprite list when i go to select source image
its so strange... im certain ive always done it this way
not sure if something changed or if im missing something here
seems like it lets me add it as texture in RawImage component...
even tho the texture type is Sprite
sprite mode is multiple
set it to single
oh man
thank you... completely overlooked that 😄
i have a "yield return new WaitForSeconds(x)" in my code, where x is variable.
im looking for a way to accurately see how far along the waitforseconds is (say returns 4 in a 7 second timer) so i can apply this to a progress bar in the UI. what would be the simplest way of doing this, or should i use a different method for the progress bar alltogether?
don't use WaitForSeconds if you want to track it like that, just use a deltaTime timer in a loop
If you know the duration, the UI can update itself
or work out the progress each refresh
how so?
I didnt read more above but if you know when something began and its duration you know the progress/end time
float progress = (Time.time - startTime) / duration;
but tbh it'd just be more direct to do the wait yourself and update the UI accordingly
progressBar.min = 0;
progressBar.max = x;
float elapsed = 0;
while (elapsed < x) {
elapsed += Time.deltaTime;
progressBar.value = elapsed;
yield return null;
}
@hasty tundra to add to this; Unity has Time.time. You can save a timestamp when a timer should end (a second is Time.time + 1f). Then in an Update method you can check if your current Time.time exceeded this. Additionally, it's very easy to calculate the difference with this.
Timestamps are one of the best ways to handle intervals, you see the documentation of Unity also lists a good example on this.
So you can either use timestmaps and calculate from there, or use boxfriend's approach and hold a variable which is incremented constantly in an Update method using deltaTime
Timer.time
yeah you typo'd it the first time lol, i was pointing it out
Is this a Yay or nay for top down pixel 2D Game?
Or in other words, is there a better way of doing this
Consider asking in #🏃┃animation or #💻┃unity-talk
This is the beginner coding channel
Sure my bad, I Just sent it here becasue I am a begginer : )
this is the beginner-level coding channel, not a general channel for beginners
@tulip scroll Please stop crossposting, and you can use !collab to find people to team with.
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
im not seeing it i dont think
this is not how you combine strings. the second parameter for Debug.Log is supposed to be a UnityEngine.Object so that the object is highlighted when you click the log.
The second parameter of Debug Log does not take a String
-# fyi, it's not + in every language :)
i got so used to using , and + interchangeably on python it didnt even click in my head it would be looking for another parameter
wdym, they aren't interchangable in python
i cant tell if thats me being stupid or me being lucky then
my teacher never seemed concerned
you can do "string a" "string b" in python, maybe that's what you're thinking about? but only for literals though
or maybe you're only thinking of print?
specifically print
yeah print(a, b) would be like print(str(a) + sep + str(b))
but it's still not the same
String interpolation is king:
Debug.Log($"Player is making noise by stepping on {name}");```
Noted
Howdy folks, I have this simple inspect item script but I'm not sure where it's gone wrong (I did follow a tutorial) The object doesn't seem to react at all to holding down the mouse and moving
And no errors
What do you see in the console while it's running
Do you see your logs?
In this tutorial, I’ll walk you through the process of developing a 3D object inspection system in Unity, similar to the ones seen in games like Counter-Strike, Valorant, and Resident Evil. You’ll learn how to interact with objects in a 3D environment, rotate them and inspect them from every angle.
This feature is perfect for inventory syst...
this is what i followed
Also I think your multiplication of the rotations is in the incorrect order
Also make sure you have set rotation speed to something non zero in the inspector
Maybe something else is changing the rotation of the object, like an animation.
Nah its just uh
one sec
an object attached to player camera view
so its infront of your face
what object is "Big Version"?
try removing deltaTime and/or increasing rotation speed
Also - do you have a script for the "holding the object" thing?
That script might be setting the rotation of the held object as well
So i set the rotation speed to 200
and its kinda just twitching out, when i hold click and drag around
did you remove deltaTime like I mentioned?
Just working on that now
(and when you do, you should reduce the rotation speed as well)
My unity decided to poop itself, 'Reloading domain' 1 min 30 seconds after saving that script
fml
Hey this is what i'm getting
Rotation speed 5
Inspecting false is just a bool which stops the character controller from being able to move/look around while inspecting
again do you have another script somewhere for the holding part?
The only script I have regarding this is the script to make this object appear
i'll show that one sec
This is what happens when you click on the 'small version' on the table
Wait
how is that object positioned in front of your face
Realisticlally you should be using mouse delta insteasd of position anyway
but yea
Question: I recognize that Unity can have multiple Input devices (M&K, Controller, etc), and each device can send inputs to the InputSystem simultaneously though in a single-player game, this usually wouldn't happen.
When setting up a control script for an object, does the Update function typically consider both kinds of inputs at all times? (Mouse, Gamepad stick, Joystick, etc)? Or do developers "toggle" between the active control scheme?
you can do it while it's locked if you use mouse delta
I would prefer to have the cursor invisible yeah
You can configure it to do either.
am i not already using mouse delta?
Wait. I just realized. Does the InputSystem return a Vector value for "movement" independent of the mouse or stick...
basically get rid of all the mouse position stuff and just replace it with:
float RotationX = Input.GetAxis("Mouse X") * rotationSpeed;
float RotationY = Input.GetAxis("Mouse Y") * rotationSpeed;```
It all depends on how you configure it.
but yes, it can.
Ok, thanks!
So it sorta works but it's kinda drunk lol
It's pivot is in it's middle, just checked
how did you check
you cut off important parts of this screenshot
Is your tool handle position set to Pivot, or Center?
Oh snap!
the pivots at the bottom
I dont think I have ever changed a pivot point
I'm not even sure why it would be down there
to place it on the table easier
Oh! that makes sense
how does one change the pivot point of this 'none table version'
Two options:
- move the Renderer to a child object and adjust its local position such that visually the pivot of the parent is in the center
- Modify the model in Blender to change the pivot
the first one will be easier if you're sharing one model with both versions of the object
Okay so it's in a parent now with a pivot in the middle, and i'll control it's parent with the movement script instead
What's the difference between straight up disabling the game object and disabling all components that allow it to interact with everything else in the scene?
hey do anyone know how to set up animations for my character in unity? the animations already exist but idk how to set them up
don't crosspost
wdym?
BIG difference. If you disable the GameObject, any scripts on the game object can't fire. So if you have a GameObjectController script, for instance, not even THAT can determine whether you enable/disable its components.
Okay we are getting somewhere, But the movement is still completely off it seems
Moving right to left and it barrel rolls over it's own top
oh ya i forgot about that, another question is like if I have a script that calls a coroutine, and I disable the script, will the currently running coroutines keep firing
don't post the same question across multiple channels
post in the correct place, once
or will they only stop when I disable the gameobject itself
that place being #🏃┃animation
This I don't know. xD

o7
Coroutines are also stopped when the MonoBehaviour is destroyed or if the GameObject the MonoBehaviour is attached to is disabled. Coroutines are not stopped when a MonoBehaviour is disabled.
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/MonoBehaviour.StartCoroutine.html
gameobjects aren't disabled, fyi, they're set active or inactive
weird terminology thing
the docs is wrong here too lol
also components being enabled/disabled just affects a few messages (ie start, update, fixedupdate, and a few others), it doesn't actually paralyze the entire script
Hello i want to Instantiate prefabs every time the coroutine is called with a random time. it work perfectly for the first Instantiate if the time for exemple is equal to 2 seconds my program will wait 2 seconds before instantiate the first prefab but then it dont wait. Its like my coroutine dont want to work 🥲
private float randCoord;
private float randTime;
private int randChoose;
bool ready = false;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
randChoose = Random.Range(0, obstacle.Length);
Debug.Log(randChoose);
randCoord = Random.Range(-4.6f,4.6f);
randTime = Random.Range(2f, 5.5f);
Debug.Log(randTime);
StartCoroutine(dela(randTime));
}
IEnumerator dela(float tm)
{
yield return new WaitForSeconds(tm);
Debug.Log("Le delai a eu lieu");
Instantiate(obstacle[randChoose], new Vector3(gameObject.transform.position.x,gameObject.transform.position.y,randCoord), gameObject.transform.rotation);
}
}```
you're starting the coroutine every frame
oh
so every frame, you schedule a new one to spawn with a delay
ok i see so i should call the coroutine inside the coroutine ?
i mean you could, but that wouldn't be very readable
so what should i have to do ?
you basically have 2 things operating over time here, the update loop and the WaitForSeconds within the coroutine
you should restructure so only 1 time loop exists
either:
- no coroutine, you have a timer variable, in update you branch:
- if there's an active timer, wait
- if not, spawn, set a new timer with a random wait time
- or, coroutine called from
Start, with awhileloop to keep doing the loop:- use
WaitForSecondswith a random wait time - spawn
- repeat
- use
something like this is ok ?
private float randCoord;
private float randTime;
private int randChoose;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
StartCoroutine(dela());
}
// Update is called once per frame
void Update()
{
}
IEnumerator dela()
{
randChoose = Random.Range(0, obstacle.Length);
Debug.Log(randChoose);
randCoord = Random.Range(-4.6f,4.6f);
randTime = Random.Range(2f, 5.5f);
Debug.Log(randTime);
yield return new WaitForSeconds(randTime);
Instantiate(obstacle[randChoose], new Vector3(gameObject.transform.position.x,gameObject.transform.position.y,randCoord), gameObject.transform.rotation);
StartCoroutine(dela());
}```
Where can i ask for a good tree pack?
better to use a loop than to StartCoroutine again
sure, i guess? but making it a loop instead of recursive would make it more readable, generally
Question: I'm doing some simple UI stuff, where I have a RectTransform object and a "pen" as a child object. I want the pen to be bound by the limits of the RectTransform (so when the player moves the mouse outside of the RectTransform, the pen stops at the edge) Similarly, if the player moves the gamepad stick to the edge of the RectTransform, the pen sticks at the edge.
Is there no function built into Unity by default that checks whether a point in space is inside of a RectTransform or RectTransform.rect?
{
while (true)
{
randChoose = Random.Range(0, obstacle.Length);
Debug.Log(randChoose);
randCoord = Random.Range(-4.6f,4.6f);
randTime = Random.Range(2f, 5.5f);
Debug.Log(randTime);
yield return new WaitForSeconds(randTime);
Instantiate(obstacle[randChoose], new Vector3(gameObject.transform.position.x,gameObject.transform.position.y,randCoord), gameObject.transform.rotation);
}
}```
https://docs.unity3d.com/ScriptReference/Rect.Contains.html
though you'd probably want to just clamp here, in which case, https://docs.unity3d.com/ScriptReference/Mathf.Clamp.html
weird how Vector2Int has a built-in Clamp method but Vector2 doesn't...
i mean you could write your own extension method if you want to i guess
Clamp basically limits the maximum value, to a value of my choosing, right?
(and minimum value)
Got it. I'll take a look, thanks!
yeah
Man, Clamp is the kind of thing that COMPLETELY changes how you approach programming challenges.
Though I'm still working through the pros and cons. Technically with Clamp the way I've implemented it, if the mouse is outside the RectTransform, the pen moves inside.
Which might not be ideal.
But I'm working through it. Thanks for the guidance.
you should probably have a virtual cursor like you do with the controller case?
just taking the delta of the mouse
When you say "virtual cursor" is that a Unity concept? Or do you mean a GameObject that works like a virtual cursor?
I think that's what I've done. But I'm not sure. In your mind, is that different than the "pen" object I mentioned above?
(though for the latter i don't think you'd necessarily need a separate gameobject, just a position could suffice)
Right.
well, im confused about what you mean here
if the mouse is outside the RectTransform, the pen moves inside.
Yeah, sorry, I'm realizing that we're both imagining the use of Clamp differently. I think I took it and applied it as a **replacement **of my previous movement logic which was
"What's the last valid position of the pen?"
"What's the normalized moveDir from the GameInput?"
if lastValidPosition + moveDir is outside of the RectTransform, do nothing. Otherwise, set newPosition to lastValidPosition + moveDir, and set lastValidPosition to newPosition
Basically, if can't move to a new spot inside the RectTransform, don't move at all.
I replaced that with "NewPosition.x = Clamp(Blahblahblah.x) and NewPosition.y = Clamp(blahblahblah.y)" Which, when the mouse moves outside of the RectTransform, the pen moves too, if able.
But to be honest, neither of these are perfectly appropriate for the circumstances. I'm still working that part out.
(Also, tbh, I'm so new to Unity, and there are 10,000,000 ways to do the same thing, that I might not be explaining the situation well enough to be understood over the internet. 🙂 )
ah no what i'm thinking is basically treating the canvas space like a screen
if you go to the bottom, no matter how far you try to move past that boundary, when you go up again, you leave the screen edge
so basically, new position = clamp(old position + delta)
so if you move the mouse diagonally, you'd still be able to move in the direction not bounded by the screen edge
Right! Absolutely.
Yeah sorry, that was included in the blahblahblah.
I mean, how could you not understand that? 😉
ah, ok. wasn't sure what that entailed lol
Haha
We're all good. I'm on the right path now thanks to you. I appreciate it - really.
Like an insane person, I decided to program the absolute most difficult part of this game FIRST. Before literally anything else.
And I feel like...if I still want to make this game after all this, that's a good sign.
I actually don't think it's gonna be good enough to be comercial, tbh. I barely know how I am going to handle saving data, so yeah, localization goes a bit out of my reach
When I destroy a GameObject (I know it's a bit more complex than this but bear with me) does Unity automatically destroy its child objects as well? If my class creates two objects, one that's a parent of another, should that class ALSO destroy those objects? Or simply destroy the parent?
destroying a gameobject also destroys its children
If
objis a GameObject, it destroys the GameObject, all its components and all transform children of the GameObject.
https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Object.Destroy.html
Guys, I don't know what to do. Every time I try to install a version of Unity, Unity Hub fills up the RAM and the installation is interrupted.
Is there any difference between Throw Exception and Debug.Assert, besides the fact that the latter gets removed at build time? Which one are you using for your projects?
throw just throws exception
Assert evaluates a result no ?
they have completely different use cases. Debug.Assert is for things that are never ever supposed to happen at runtime.
exceptions are sometimes expected to happen at runtime
if this is the whole story then things are simple, tx
I just use prints with the type of warning it is lol in like "Invoking object that does not exist!" or something like that
I've got a quick best practices question: I have a Class called "Draw Shape", which is responsible for allowing the player to draw a shape on a UI element, and then it processes that shape info and returns a value. It instantiates a UI element to be drawn on, and a pen to draw on it. Because the pen is controlled by the player, the pen has its own PenController class that converts GameInputs into movement.
This PenController class needs the GameInput singleton, but because it's being instantiated by my "Draw Shape" class, it doesn't know that GameInputs exists. **What's the best way to pass the GameInput singleton to an instance of a class instantiated in runtime? **
why doesn't it know that GameInput exists?
it's a singleton, it should be available everywhere
you shouldn't need to pass it around anywhere (unless you have race conditions on initialization)
This is the element I don't quite understand. So Singletons are like..."global classes/functions"?
basically, yes
Ok, that's awesome.
it's why the public static Instance is part of the singleton pattern
A large draw of using SIngletons is just to be able to use a static accessor property. Use that.
So next question, which is a precursor to this one: Is it "best practice" for GameInput to be a singleton?
I assumed so.
needs more context to really answer
Not really - they are objects of which there is only a single instance at a time, and there is a "global" accessor variable you can use to access this single instance. So effectively yes, but technically not really.
Because ultimately, there's only one of them (per player, but we'll get to that)
It's not really clear what "GameInput" actually does
per player
then it probably should not be a singleton
the concept of a singleton is that a single entity exists throughout the lifetime of the runtime, and that it's accessible whenever/wherever
GameInput is my logical class between the Unity Input Action system and my other classes. It publishes events for the various actions triggered by the Input Action asset.
so if multiple players is a possibility, and they should all have separate GameInputs, that violates what a singleton does
Got it. That makes sense.
I would recommend against that pattern. I think you're falling into a common trap with that. You're essentially duplicating your work for little benefit.
It should do one thing and one thing only - just manage and share the single instance (per player) of your InputActionsAsset (and/or the generated C# wrapper class around it)
So then - that's my reason why the class doesn't know what GameInput is. And I'm gonna make GameInput NOT a singleton.. 😂
so then back to your original question; the thing doing the instantiation would have a reference to the component, and then it would assign that reference in when it does the instantiation
though another thing to consider: do you really need to instantiate it every time?
could you instead just have a single instance that you show/hide/clear as necessary?
I think we're saying the same thing, but using different words. That's what it does, I think. If by "manage" you mean "takes the actions triggered by the InputActionsAsset and makes them "available" to other classes.
and if you have a player prefab or something along those lines, it could have a direct serialized reference to its own input component
Are you creating/exposing events from the GameInput class?
I considered this. Basically, the player will only have this pen and paper when the item is equipped. And it's very very likely that a player may NEVER equip it.
or just the instance of the actions asset itself
So I could instantiate the objects on equipping the item. And destroy them when unequipping them. Absolutely.
Here's a snippet from inside the GameInput class:
`public event EventHandler OnInteractAction;
public event EventHandler OnInteractAlternateAction;
public event EventHandler<InventorySlotByKeyEventArgs> OnChangeSelectedInventorySlotByKey;
public event EventHandler<InventorySlotByScrollWheelEventArgs> OnChangeSelectedInventorySlotByScrollWheel;
public event EventHandler OnOpenCloseMainInventoryAction;
public event EventHandler OnUnequipAction;
public event EventHandler OnAttackPrimaryAction;
public event EventHandler<LookVectorEventArgs> OnLookAction;
private InputSystem_Actions inputSystemActions;
private void Awake() {
inputSystemActions = new InputSystem_Actions();
inputSystemActions.Player.Enable();
Debug.Log(inputSystemActions.Player.Interact);
inputSystemActions.Player.Interact.performed += Interact_performed;
inputSystemActions.Player.InteractAlternate.performed += InteractAlternate_performed;
inputSystemActions.Player.InventorySlotByKey.performed += InventorySlotChangeByKey_performed;
inputSystemActions.Player.InventorySlotByScrollWheel.performed += InventorySlotChangeByScrollWheel_performed;
inputSystemActions.Player.OpenCloseMainInventory.performed += OpenCloseMainInventory_performed;
inputSystemActions.Player.Unequip.performed += Unequip_performed;
inputSystemActions.Player.AttackPrimary.performed += AttackPrimary_performed;
inputSystemActions.Player.Look.performed += Look_performed;
}
private void Interact_performed(UnityEngine.InputSystem.InputAction.CallbackContext obj) {
Debug.Log("InteractPerformed in GameInput");
OnInteractAction?.Invoke(this, EventArgs.Empty);
}`
or you could have object pooling to avoid creating a lot of garbage if a player spams equipping and unequipping
Yeah all of those events are duplicated
This interests me. What would that entail?
if you just did:
public InputSystem_Actions Actions => inputSystemActions;```
Then your other scripts can subscribe to whatever they want easily:
```cs
void OnEnable() {
GameInput.Instance.Actions.Interact.performed += MyInteractionHandler;
}```
They also are free to then do things like subscribe to the other events (.e.g `started`, `canceled`) or even to poll actions in Update. Plus you don't have to write a duplicate event for every actions.
These duplicate events are just making busywork for you while also limiting your options @odd remnant
Question, does the garbage collection happen when instanciating/destroying components or just with objects?
in the most basic scenario, just an instance of a canvas that isn't destroyed, instead just initialized when you equip the item
there's a lot of ways you could expand on that
could have a static pool for all instances of the item, could have that object just specific to each instance of the item, etc
depends on how exactly the item works i suppose
components are objects
though to be specific, garbage occurs only with reference-type objects (which unity objects are), not with value-type objects
Thanks, I'm gonna consider that down the road. Because I still haven't implemented object equipping yet. I did end up needing to do a performance pass on the code though because I was doing some icky things like multiple GetComponent calls.
also another point- garbage being created and garbage being collected don't happen at the same time.
i don't fully understand how mono specifically does it (each runtime is unique) but generally garbage collection happens in sweeps
Aren't isntances of components also reference type???
yes i said that, maybe i phrased that poorly
im trying to say 3 things there
- components are also objects
- garbage occurs only with ref types
- components are also ref types
more broadly, any unity Object is ref type
that includes GOs, SOs, components (and probably a few other things i don't know about)
Ok, I'm reading, but not understanding. But I want to! I think what you're saying is that I'm basically "duplicating" the action from the InputSystem_Actions asset. That InputSystem_Actions already makes available an event (which this GameInput class is taking, and making its OWN event).
But if GameInput just made inputSystemActions a public object, my classes could subscribe to those actions directly.
So I'll fully admit, where I got the structure for the GameInput class is from the CodeMonkey tutorial and I 100% own up to "doing, but not understanding why doing it THIS way is necessary" beyond the ease of following the tutorial.
So how do you avoid garbage creation when adding and removing components?
Is there... a component pooling?
you can't
don't think so, no
i don't know how that'd even work tbh, since you can't like AddComponent a component instance
I guess you could technically have the components on pooled objects, but seems pretty convoluted
in general you try to design stuff to not require unnecessary garbage
yeah that's what im thinking
(object pooling is one said design pattern)
pool the game-objects instead of the components
you can still use the main component as the reference but enable/disable the gameobject
@naive pawn I've been thinking about this idea of when/whether to instantiate/destroy the drawing surface and pen. And it's leading me to this question:
Top level. Let's say there's two options (there's millions but let's narrow it down to two):
-
Option 1: I create a canvas, UI Element, and Pen Object when the player loads the game, and these are activated or made available for use when the player equips the Wand.
-
Option 2: When the player equips the wand, the canvas, UI Element, and Pen object are instantiated and wait to be used.
PC resources-wise/Game Performance-wise, what decision am I ultimately making? "Performance" is a big word. And I know that creating objects requires some amount of PC resources. What is it that I'm deciding - behind the scenes - when it comes to performance?
My vague understanding is that objects that are instantiated are saved in memory. Is that...some amount of RAM? And that instantiating objects requires processing power (is that...CPU/GPU processing?)
Yea when we make a copy of an object, it takes work and memory allocation to make it and set it up.
Doing it once and simply hiding the object when not in use prevents this in future
for this situation id say its probably fine to spawn when needed and destroy later but if you notice a lag spike during this then you may want to spawn once and keep (profiler will let you see this)
Got it. Yeah, where my knowledge/understanding of things here ends is what the "overhead" is of a particular object. When I think about it, this is really really small beans: it's an empty canvas, an invisible gameobject (which...I have concerns about the cost of that on the GPU), and a game object that represents a pen. So it's really, really low compartively to other elements of the game.
And that leads to my next question: right now the object that players "draw on" - remember, this is never visible to the player - is a GameObject with an Image component. If I understand right, assuming my code never references an "Image" component, I can just...delete that component, and use the RectTransform. Which should save me on GPU processing of a see-through image. Right?
yes but ugui may already cull and not draw a fully transparent Image but yea if its not being used it can be removed
Ok sweet.
1 quad wont cause any noticable perf loss though
so you know, UGUI canvases will re process the mesh when something changes only so if you have other UI things there too its best to use sub canvases where it makes sense to help split things up
e.g. main canvas with HUD canvas and pause menu canvas
well yea it will draw each frame but mesh recalculation/re creation cpu side is only when things change
this explains it better than i did: https://unity.com/how-to/unity-ui-optimization-tips
For multiplayer games (or just in general) do people tend to create a "PlayerSettings" class to hold the value of their settings. Or put those right on their PlayerClass?
that should be a separate class
And then when we eventually get to Loading/Saving, I know that loading and Saving the game will likely be a function of another class. But should the Settings class have its own Load/Save functions? I'm trying to nail down how to separate class functions properly.
Probably the player settings should be something that is directly saved as playerprefs, and then the save systems handles the big stuff if any (usually small multiplayers don't have much to save there since they are mostly separated matches and MAYBE a simple progression system)
PlayerPrefs is a Unity thing right?
Is basically a supersimple store file for basic info, nothing big or delicate should be saved there
i wouldnt use playerprefs at all. you're going to be setting up a different save system for actual data anyways. No reason to mix between 2 systems when playerprefs is worse in every way
I would say it is fine to use for stuff like the basic config settings, it's alright
How does PlayerPrefs "work" though. Does it get saved on the client's computer? Or is it only used within Unity development?
It's stored in the Registry
sure if thats how you want to set it up. The actual writing/reading to file should be in one place like a save manager. If your settings class wants to load the data, it can ask the save manager for the data
Or some game manager class could load the settings from the save manager, and initialize your settings class. Ultimately the same result but might change how you write the methods, or how the save manager knows what to read/write
Ok sweet. Thanks!
https://docs.unity3d.com/ScriptReference/PlayerPrefs.html the docs list where player prefs actually saves stuff
Still wouldnt bother using it. theres really just no point if you're going to be writing to file for other reasons
PlayerPrefs pretty good for saving things like a login session authtokens
I use it in game jams... and for actual player prefs if every other piece of save data is going to a server. That has the added benefit of letting a user keep device-specific prefs, which isn't everyone, but it's nice for folks who care about that.
Yes
i'm currently having a issue regarding Unity on Linux because my main player object is not rendering and any 3D object that has a shape of a capsule doesn't render, can you guys help me out here?
You have it hidden
Look at the eyeballs in the left margin of the hierarchy window
@wintry quarry tried it again and made sure it was visible, didn't actually render either way
Look at the selected object
it's shown as visible, even though it didn't even render
I didn't have these sorts of issues on the Windows version of Unity
Change this to "Pivot", then you'll see the gizmo where the object actually is
Make sure it's not just somewhere else
As a side note, i'm using the built in renderer (which shouldn't had this issue in the first place)
Anyone have any simple 3d game ideas, but could become really crazy with some tweaks?
this is a code channel
So I know that a child object's position and rotation are tied to the local position and rotation of their parent. I have a First-Person camera, and as a child of that, a Right Hand Equipment slot, and then a Game Object in that slot that's the equipment. When the player moves left and right, I want that equipment to lag behind the player's movement. How would I start going about that? Do I have to break the parent-child relationship first?
unparent them and make them follow a transform under the character with a custom script that adds a slight delay or smoothing
Ok perfect. As I was writing it I was starting to see how it might work. So the camera should have a child that represents the item's "targetlocation", and then an unparented GameObject elsewhere would have in its script, the direction to move toward that position.
some simple lag can be done like this currentPos = Mathf.Lerp(currentPos, targetPos, Mathf.Exp(-sharpness * Time.deltaTime), sharpness is typically in the range 1 to 10
And sharpness is a float here? Something I define to determine how sharp the interpolation is?
Hello! What would be the best way to load a lot of photos from a folder?
some explanations on whats going on there: https://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
because the way i am doing it right now, loading it in a loading scene - and then saving the references causes a lot of GC and Frame drops
string folderPath = Application.persistentDataPath + "/Photos";
string[] photoFiles = Directory.Exists(folderPath) ? Directory.GetFiles(folderPath, "*.png") : Array.Empty<string>();
byte[] textureData = File.ReadAllBytes(photoFiles[photoNr]);
Texture2D texture = new(2, 2);
if (texture.LoadImage(textureData))
{
Photos.Add(Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f)));
}
the best simple way is this: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Networking.UnityWebRequestTexture.GetTexture.html
but its not the ultimate fast and efficient way (which is annoyingly complicated)
but i am getting it from persons computer
doesnt matter, you can use any url, even a local file path
oh ok
the point here is not speed however, its leveraging the async smoothness this provides. You can probably find an async image loader library on github and maybe DIY something more elegant from there.
Is there any way to change the "default" transform of an object while playing the game? I know I can copy component and paste component but it's suuuuuch a hassle sometimes.
i mean you could make a editor extension
wait while playing the game??? wdym by changing the default transform???
While playing, yeah.
Well, while previewing.
For instance, I'm creating a "hold position" for a piece of equipment, which requires me to press Play to see where my hand - which is animated using TwoBoneIKConstraint - will sit on it. I can view the game on one screen, and adjust the transform of the HoldPosition. on the Scene view. But I have to remember to Copy Component and Paste Component Values after adjusting things, plus I can only adjust one component at a time.
ah for that you definetly need to make your own editor extension or just copy paste component i guess, i guess you could copy the gameobject itself instead of components but thats specific scenario since when you play scripts could change things up and so on
Yeah. Alright! Thanks!
Is this 3D?
Is it bad to daisy-chain my coroutines? If I want event A then event B, then event C. But I need to wait to continue, is this bad code practise? Is there a better way to do this? Im trying to make a huge story game.
void Start()
{
StartCoroutine(TurnLightsOn());
}
void Update()
{
}
IEnumerator TurnLightsOn()
{
yield return new WaitForSeconds(0.5f);
_light1.gameObject.SetActive(true);
soundManager.PlaySfx(0);
yield return new WaitForSeconds(2f);
_light2.gameObject.SetActive(true);
soundManager.PlaySfx(0);
yield return new WaitForSeconds(2f);
StartCoroutine(AskInitialQuestions());
yield return null;
}
private IEnumerator AskInitialQuestions()
{
yield return new WaitForSeconds(2f);
soundManager.NextVoiceClip();
}```
you can yeild coroutines btw
what do you mean by this ?
like yield return AskInitialQuestions()
you can but don't have to if you just write it like above
yield return StartCoroutine ( AskInitialQuestions()) also works
both return Coroutine
this has example too https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Coroutine.html
