#💻┃code-beginner

1 messages · Page 659 of 1

north kiln
#

are you using a normal shader or something custom

rotund crown
#

standard shader

north kiln
#

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

rotund crown
#

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

toxic cove
#

!docs

eternal falconBOT
toxic cove
#

where should I go to learn C#

wintry quarry
wintry quarry
#

learning C# will help you with Unity

toxic cove
#

Oh.

#

I don't even know it looks hard and confusing to me

#

C#.

wintry quarry
#

You either want to put in the effort or you don't ¯_(ツ)_/¯

toxic cove
wintry quarry
toxic cove
tight oak
#

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? :[

teal viper
tight oak
#

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 :[

teal viper
eternal falconBOT
teal viper
tight oak
#

Nope notlikethis

teal viper
#

Can you take a screenshot of your console?

#

After it's supposed to trigger.

tight oak
#

Sure! The only messages I seem to get are the two first debug logs

teal viper
#

Make it a habit to show people the whole context. Don't cut screenshots in the middle.

tight oak
#

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

teal viper
#

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.

teal viper
#

Because they're triggers obviously.

teal viper
north kiln
#

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

nocturne hawk
#

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?

polar acorn
# north kiln

Also every object with GetComponent has a .transform method so you never need to use GetComponent<Transform>(), just use .transform

foggy spade
#
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
teal viper
teal viper
median hatch
#

just make sure to practice your logic skills and to not copy code you dont understand

tepid idol
#

I just installed Google Sign plugin in to my unity project and got all these errors. Any idea how to fix it?

keen dew
#

The screenshot is unreadable

hexed terrace
alpine summit
#

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

sour fulcrum
#

yes.. but if you mean via inspector no for dictionaries by default

naive pawn
alpine summit
#

ah

naive pawn
#

you could use the SerializedDictionary plugin, but for something like this i would probably just log it out manually to check

alpine summit
#

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

sour fulcrum
#

in general you can use [SerializeField] with a private or protected accessor

alpine summit
#

except when the attribute is not serializable, got it

sour fulcrum
#

things being public make it serliazable implicitly, which lets it be viewed in the inspector as a by product

sour fulcrum
#

is that not what its called

#

going off 4 hours sleep back to back sorry

naive pawn
#

"accessor" is an umbrella term for getters and setters, for properties in the case of c#

sour fulcrum
#

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

naive pawn
#

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"

alpine summit
naive pawn
#

it doesn't override name, it just shadows it

#

it creates a new name of the current class instead of using the inherited name

alpine summit
#

is there any way to make ToString reference the new name in subclasses, without having to duplicate the code to each one?

naive pawn
#

(btw, string interpolation would probably make this more readable at a glance, that might be what the suggestion on String there is saying)

naive pawn
alpine summit
#

this Action class represents an action that can be taken in my game, so it's inherited by classes that implement specific behaviour

naive pawn
#

-# 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

alpine summit
#

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

naive pawn
#

ok, and why isn't that using the existing field

#

do you set the name in the inspector or something

alpine summit
naive pawn
#

what's the purpose of the new name field?

alpine summit
#

ok hold on

naive pawn
teal viper
#

Why not just reuse the existing name field from the base class?

alpine summit
#

let me show my code and maybe that will help explain my intention

naive pawn
#

!code

eternal falconBOT
alpine summit
#
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);
    }
}
naive pawn
#

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

alpine summit
#

I see

naive pawn
#

instead of using the existing name field that Action knows about

#

you would use the Action's name field to set names

sour fulcrum
#

to be 100% clear incase your unaware, you can access values declared in classes your inheriting (assuming the access modifier isn't private)

burnt vapor
naive pawn
#

you could either set the name directly in the constructor of each subclass, or you could specify another constructor overload which accepts a name

burnt vapor
#

Use the proper convention, make it virtual and override name

teal viper
#

You could use a Name property and override it in the sub sclasses.

sour fulcrum
naive pawn
#

(no i mean if it's internal or private then you can't access from a subclass)

alpine summit
sour fulcrum
#

internal should work?

naive pawn
burnt vapor
naive pawn
#

ah

sour fulcrum
#

internal is namespace scope, no?

burnt vapor
#

No

#

Project scope

teal viper
#

Assembly

naive pawn
# sour fulcrum internal should work?

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

burnt vapor
#

You could argue file is namespace scope, but this is specifically scoped to files

#

There's no such thing as namespace scope

naive pawn
#

also private protected apparently

#

why does c# have so many access levels damn

burnt vapor
#

private protected just means it's private to a class, but derived classes can also access it within the same assembly

naive pawn
#

that would be protected

alpine summit
naive pawn
sour fulcrum
#

petitioning parole as a new namespace scoped modifier 😛

naive pawn
#

could be name => "GenericAction"

burnt vapor
#

Unless you want to mutate this

alpine summit
#

I see

#

it's cool that you can omit the setter

burnt vapor
#

Well yeah it's technically just a method string Get_Name() in this case

alpine summit
#

so subclasses should pretty much duplicate this line, just replacing virtual with override, correct?

burnt vapor
#

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.

alpine summit
#

tysm for the help

#

and I can confirm that the console log works correctly now

burnt vapor
#

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)

naive pawn
#

-# well, maybe except for extending MonoBehaviour lol

sour fulcrum
#

instansiating scriptableobjects at runtime go brrr

burnt vapor
#

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

alpine summit
#

one more question, I'm struggling to override Equals so that it checks whether the other object is the same subclass of Action

burnt vapor
#

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

alpine summit
#

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

burnt vapor
#

Then compare GetType() of Move against GetType() of Score

#

The Type type in C# will properly compare against its own type.

alpine summit
#

ok thanks, GetType() is what I was looking for

real rock
#

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

burnt vapor
# alpine summit nice

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)

hexed terrace
real rock
hexed terrace
#

You generally don't move and reset the value after moving.. unless you want it to now stop moving

shut swallow
#
            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

toxic cove
#

like for example where it'll show what instantiate does etc

slender nymph
#

!docs

eternal falconBOT
ancient hearth
#

Are there any free ways to work on a project with multiple people, and have a way to store assets?

slender nymph
#

not really a code question, but use version control like git or unity version control

ancient hearth
keen cargo
#

Github

ancient hearth
keen cargo
#

Mine does

ancient hearth
#

It offers 1gb iirc

slender nymph
#

you recall incorrectly

ancient hearth
keen cargo
#

3d

#

And I don't have LFS set up

ancient hearth
#

I couldn't even push an empty project there

keen cargo
#

You didn't set up the git ignore correctly then

slender nymph
ancient hearth
keen cargo
#

It does work without it

slender nymph
#

what? without LFS? sure as long as you don't have files over 100mb

ancient hearth
#

Without a library folder

keen cargo
#

Yes

#

Unity generates them for you

slender nymph
#

the library folder is automatically generated by the editor

ancient hearth
#

Ahhh

#

Which files should I gitignore?

keen cargo
#

If you do it on GitHub then you can just choose "Unity" in the gitignore list

quaint kestrel
#

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.

polar acorn
quaint kestrel
leaden ridge
#

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?

polar acorn
quaint kestrel
#

that didn't fix the problem unfortunately. What could possibly cause this issue that aren't my classes.

eternal needle
polar acorn
leaden ridge
quaint kestrel
eternal needle
polar acorn
leaden ridge
cinder ingot
#

Let me understand this, you're trying to compare a player drawn shape to an image?

eternal needle
leaden ridge
polar acorn
quaint kestrel
polar acorn
quaint kestrel
#

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?

quaint kestrel
polar acorn
quaint kestrel
polar acorn
quaint kestrel
#

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.

quaint kestrel
#

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.

quaint kestrel
#

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

polar acorn
#

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

quaint kestrel
#

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?

polar acorn
polar acorn
quaint kestrel
#

perhaps just restarting the engine could've also solved the issue. In any case it's solved now

mild osprey
#

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

polar acorn
#

!ide

eternal falconBOT
polar acorn
#

But if you want to see if it's working just... try it?

#

Oh, woops, wrong command

#

!code

eternal falconBOT
polar acorn
#

I don't know why I did IDE, I think I need more caffeine

mild osprey
#

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

polar acorn
mild osprey
#

So I got the camera on the player and the camera can rotate but doesn't move with WASD

polar acorn
#

Show the inspector of this object

mild osprey
polar acorn
mild osprey
#

In the link I provided

polar acorn
#

No, on the object

mild osprey
#

or you still mean in the inspector

#

Oh ok my bad

polar acorn
# mild osprey

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

mild osprey
#

Well that's what the guy showed in his video lmao but let me try and see if that does it

polar acorn
mild osprey
#

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

alpine summit
#

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

ashen arch
alpine summit
#

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

ashen arch
#
bool waitingForInput = true;
void Update() {
  if (!waitingForInput) {
    acceptInput = true;
  }
}
alpine summit
#

this won't work for my use case, since I still need to run more code after the button is clicked

eternal needle
#

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

final forge
#

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

eternal needle
#

you would yield until receiving the input

brave robin
final forge
#

Oh I see now, so it's stopped before it removes the existing speed modifier, is that right

alpine summit
eternal needle
ashen arch
final forge
#

I don't have a use case, I just want to learn how to use coroutines and how to write better code

alpine summit
brave robin
#

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.

eternal needle
alpine summit
#

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

eternal needle
brave robin
alpine summit
#

correct

ashen arch
#

You could add a while() loop to the coroutine, waiting for a bool to become true.

eternal needle
grand snow
#

Task completion sources are good for this when using async (Awaitable or UniTask)

brave robin
#

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

ashen arch
#

Contrivance's sample code is 10x better than the sh*t on that docs page bawsi linked.

alpine summit
#

does a coroutine always have a return type of IEnumerator? can a coroutine take any arguments?

brave robin
#

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

alpine summit
eternal needle
#

🤷‍♂️ people possibly being confused by basic c# doesn't make it shit.

ashen arch
#

lambda is not basic

#

non-lambda is

brave robin
alpine summit
#

I'll try async

eternal needle
# ashen arch lambda is not basic

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.

eternal needle
#

If you dont understand coroutines, you really aren't gonna succeed with async

#

And you don't need it here either

brave robin
#

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

ashen arch
#

that's why most documentation online is trash

brave robin
#

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

eternal needle
ashen arch
#

they said they knew lambda after the fact

brave robin
#

Welcome to Unity, we are very opinionated 😄

alpine summit
#

putting this in the Update loop feels a bit spaghetti, but the use case is simple enough that it should work

grand snow
#

Unitask completion source

alpine summit
#

it would still be nice to learn about some other options :P

eternal needle
#

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?

brave robin
#

Also this is code-beginner. Nothing wrong with coroutines when you're first starting out.

alpine summit
# eternal needle can you paste the code you're trying to change?
    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;
    }
brave robin
#

Boardgame essentially?

alpine summit
#

ideally the function that calls TryAction would also wait for the button press

brave robin
#

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

alpine summit
#

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

ashen arch
#

it is

eternal needle
alpine summit
#

OnLMBUp is called from AcceptInput which is called from Update. I'm sure you can infer the rest

eternal needle
#

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

alpine summit
#

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

eternal needle
alpine summit
#

ok sure, that makes sense

eternal needle
#

you would also want to move that validAction logic purely to the coroutine because I don't think it'd be used here otherwise

alpine summit
#

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

eternal needle
#

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

alpine summit
#

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?

brave robin
#

when it hits a yield it doesn't execute more code, it will come back and resume when the yielding code actually yields

polar acorn
brave robin
#

So if you are yielding on a startcoroutine, it will wait there for that coroutine to finish

alpine summit
#

I see

eternal needle
#

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

polar acorn
#

or yield return new WaitUntil(SomeBoolFunction) which will wait until that function returns true

alpine summit
#

ahh

brave robin
#

The rest of your project will continue to run as normal, it just pauses that particular method for later

alpine summit
#

ok so it works how I thought

#

how can I make the coroutine return like a normal function?

brave robin
#

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;
}
alpine summit
#

there is definitely some wrong code here

polar acorn
#

And WaitUntil takes a function that returns a boolean, not a boolean

alpine summit
#

right

#

I'm not sure why it needs a type argument here

polar acorn
alpine summit
#

that fixed it, thanks

brazen crescent
#

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");
        }
    });
}```
alpine summit
#

@eternal needle @brave robin @polar acorn got things working, thanks for the help! BlobHeart

#

wait... why is the for loop variable passed by reference? D:

naive pawn
#

that's just how it is

polar acorn
# alpine summit wait... why is the for loop variable passed by reference? D:

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

alpine summit
#

thanks

naive pawn
#

it's just the same i throughout each iteration, hence why i++ works

alpine summit
#

right, i is in scope of every loop iteration as opposed to a single one

#

makes sense

odd remnant
#

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?

polar acorn
naive pawn
#

oh i see what you're trying to say

polar acorn
#

While defining something in the body of the loop means it's a variable unique to that iteration of the loop

naive pawn
#

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

polar acorn
#

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

naive pawn
#

mm i mean, not really?

#

(to be clear, "not really" the "every language" thing)

polar acorn
#

I have at least hit it in Java, C#, Python, and Haskell

naive pawn
#

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

naive pawn
#

(but yeah i agree on the rest of what you said)

eager mesa
#

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.

odd remnant
cinder ingot
#

Raycast maybe?

naive pawn
#

(though, kind of a band aid fix that closes off some options in the future)

cinder ingot
#

Then grab the transforms and drawline between those points.

odd remnant
naive pawn
eager mesa
naive pawn
#

or maybe you would have a canvas in screenspace for that instead of world space

cinder ingot
#

Might need to fiddle with the values of a Vector3 to get the correct positions etc.

odd remnant
#

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.

odd remnant
#

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.

cinder ingot
#

You won't be able to draw the shape AND control the character at the same time.

odd remnant
#

I wouldn't be able to turn the character, no. But they could still walk around

#

Right?

cinder ingot
#

Yes.

naive pawn
#

well, keyboard and mouse input are separate, so that's up to your design choices

cinder ingot
#

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.

odd remnant
#

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.

cinder ingot
#

You could time dilate too. Slow the game when drawing or something.

odd remnant
#

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?

cinder ingot
#

It is anchored to the screen. Add a canvas and in the camera option just set it to "screen space"

naive pawn
#

the canvas renders directly onto the camera, without consideration for position or rotation as something in world-space would require

odd remnant
#

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.

cinder ingot
#

Super useful for HUD etc.

#

It only uses x and y. And always returns within 0 and your resolution set (1920 x 1080) etc.

odd remnant
#

When a canvas is drawn in Screen Space, is it possible to make the Canvas LARGER than the screen?

naive pawn
#

you don't draw a canvas in screenspace, you set it to be in screenspace
you can't control its size directly

polar acorn
naive pawn
#

maybe nested canvases could be set like that but... what's the point?

polar acorn
#

So if you want something offscreen, you can just put it outside the bounds of the canvas

odd remnant
# naive pawn maybe nested canvases could be set like that but... what's the point?

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.

naive pawn
#

isn't there a method to set the mouse position though

odd remnant
naive pawn
#

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)

eager mesa
#

Peculiar

naive pawn
#

the x rotation specifically?

eager mesa
#

rb.constraints = RigidbodyConstraints.FreezeRotationX; right?

naive pawn
#

why not just set the constraints in the inspector though

eager mesa
#

I did not know you could!

#

(How do i do that?)

naive pawn
#

..the same way you constrained the z rotation?

#

you click the checkbox

eager mesa
#

rb.constraints = RigidbodyConstraints.FreezeRotationZ;

#

I coded it,

naive pawn
#

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

tawny grove
#

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?

eager mesa
#

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?

naive pawn
#

so perhaps the ground just isn't level?

eager mesa
#

Nope, the car is running on roads which are just objects, 0, 0, 0 rotation.

#

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?

naive pawn
#

it's slightly nauseating so probably not lmao

#

maybe a little camera smoothing could make it stay a feature

eager mesa
#

Clamp the camera rotation?

naive pawn
#

anyways about your actual question i think you should start by debugging it to see what it's trying to do

naive pawn
eager mesa
naive pawn
#

sure, yeah

eager mesa
#

Because the blue car still goes down if there ins't a road underneath him

naive pawn
#

yeah

eager mesa
#

So what i could do is make the blue car NOT turn when in front of the player

naive pawn
#

check the z displacement, i guess?

eager mesa
#

The what?

#

Where the blue car spawns on the Z axis?

naive pawn
#

no, the difference of z position between the blue car and the yellow car

eager mesa
#

gameObject.transform.position = target.transform.position + new Vector3(-20f, 0f, 0f);

This should make it so it spawns directly infront the yellow car right?

naive pawn
#

oh you're driving in -X?

eager mesa
#

yup.

#

I built the roads in the wrong direction so ig im going for it now

naive pawn
#

then yeah

eager mesa
#

is that the problem?

naive pawn
naive pawn
eager mesa
#

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

naive pawn
#

well doesn't look like it

eager mesa
#

really?

eager mesa
#

i mean z axis, my apolagies

naive pawn
#

nothing in your code touches that either

eager mesa
#

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

naive pawn
#

ah

eager mesa
#

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

naive pawn
#

wait, your rigidbody is dynamic, right?

#

in that case, the rigidbody controls the transform. you shouldn't modify the transform yourself

eager mesa
#

I think so?

#

i think not so?

naive pawn
#

it's dynamic, yeah

#

for a 3d rb, dynamic and kinematic are opposites

eager mesa
#

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)

naive pawn
#

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

eager mesa
#

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?

naive pawn
#

not a very good assumption

naive pawn
#

tell the rigidbody to move the transform instead

#

the rigidbody has methods for that

#

also for the initial transform.position =

eager mesa
#

rb.transform.position = target.transform.position + new Vector3(-20f, 0f, 0f); like this?

#

so swapping out gameObject for rb?

hexed hare
#

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?

eager mesa
#

right click below where your gameobjects are -> UI -> panel, from there you can add stuff

#

watch a tutorial on it

hexed hare
eager mesa
grand snow
#

@hexed hare https://learn.unity.com/tutorial/working-with-ui-in-unity# have a read of this to learn UGUI

Unity Learn

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...

polar acorn
jolly stag
#

!code

eternal falconBOT
open apex
#

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

slender nymph
#

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

open apex
polar acorn
slender nymph
#

there are beginner c# courses pinned in this channel

open apex
#

I am just talking about vectors

slender nymph
#

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

polar acorn
ashen arch
open apex
slender nymph
#

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

open apex
hexed hare
#

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?

ashen arch
slender nymph
#

pong, flappy bird, doodle jump, simple things like that. this is also not a code question.

open apex
hexed hare
slender nymph
ashen arch
#

terraria would be more difficult because you have to worry about gravity, platforms, jumping through platforms, etc.

open apex
open apex
slender nymph
#

who is "they"? because "they" sound potentially uninformed

open apex
#

someone here

toxic cove
#

!docs

eternal falconBOT
fierce shuttle
# open apex Btw this was what I was doing at the beginning (through code academy) 😭 but the...

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

faint osprey
#
{
    progressBar.fillAmount = Mathf.Clamp01(timer / timerInterval);
}```

trying to use the fill amount value for an image but its not working
wintry quarry
#

And what debugging steps have you taken?

faint osprey
#

no dont worry its cause the image was set to none

#

so wasn't given me an option for image type

finite tendon
#

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

naive pawn
#

as for the turning, you can use torque or angular velocity

naive pawn
#

it looks like a one time thing here, so you should be using an Impulse type force instead (and probably could just be AddForce

finite tendon
#

okie i was following the unity lauch projectiles guide thing to make a cannon but i am kinda struggling

naive pawn
#

then you would incorporate the transform direction into the AddForce; the force is in world-space

frigid sequoia
#

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??

sour fulcrum
#

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

frigid sequoia
#

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??

sour fulcrum
#

i mean at some point your gonna have to iterate somewhere

#

depends more on where your storing the words

naive pawn
#

wdym by "iterating a script"

#

i don't think it means what you think it means

frigid sequoia
#

I mean "string" sry

frigid sequoia
naive pawn
#

you could use a dictionary for ~O(1)

#

either a bit less flexible or a bit less friendly than what batby showed above perhaps

sour fulcrum
#

stuff like this being automatic is good for iteration efficiency and later down the line accessibility reasons

naive pawn
sour fulcrum
#

only reason why mine wasn't a dict was lack of serialized asset usage at the time of making it iirc

frigid sequoia
naive pawn
#

at least, not in that format

frigid sequoia
#

I want numbers to also show color coded, numbers that I have no idea of what they are gonna be lol

naive pawn
#

oh boy, regex

sour fulcrum
naive pawn
naive pawn
frigid sequoia
#

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

sour fulcrum
#

i mean moreso that what makes the number a given colour

frigid sequoia
#

It would be helpful, but I assumed it would take a while

sour fulcrum
#

again what makes those numbers those colours

#

game logic wise

frigid sequoia
#

Stuff scales with a given stat, stats should have an associated color to be more readable

naive pawn
#

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>"

sour fulcrum
#

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

sour fulcrum
# sour fulcrum https://paste.mod.gg/tljgyodigous/0 full code for how this was used btw

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

frigid sequoia
#

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

sour fulcrum
#

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

frigid sequoia
#

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

sour fulcrum
#

you can update it when a change happens

#

as mentioned in a previous convo

frigid sequoia
#

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

sour fulcrum
#

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

frigid sequoia
#

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

sour fulcrum
#

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

north kiln
#

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

sour fulcrum
#

yeah my suggestion is pretty bare bones and far from a magic bullet

frigid sequoia
#

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

hallow sun
#

an idea for icons is to make a custom font and put them as symbols you're not gonna need

north kiln
#

You should just use <sprite>

frigid sequoia
#

I was about to use that, yeah

median hatch
#

its a pain in the ass but yea

dire torrent
#

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

median hatch
#

set it to single

dire torrent
#

oh man
thank you... completely overlooked that 😄

median hatch
#

no worries man

#

happens to the best

hasty tundra
#

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?

slender nymph
#

don't use WaitForSeconds if you want to track it like that, just use a deltaTime timer in a loop

grand snow
#

If you know the duration, the UI can update itself

#

or work out the progress each refresh

hasty tundra
grand snow
#

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;

naive pawn
#

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;
}
burnt vapor
#

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

burnt vapor
#

no?

#

It's definitely Time.time

naive pawn
#

yeah you typo'd it the first time lol, i was pointing it out

vocal sequoia
#

Is this a Yay or nay for top down pixel 2D Game?

#

Or in other words, is there a better way of doing this

ivory bobcat
vocal sequoia
#

Sure my bad, I Just sent it here becasue I am a begginer : )

naive pawn
frosty hound
#

@tulip scroll Please stop crossposting, and you can use !collab to find people to team with.

eternal falconBOT
#

: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

marble hemlock
#

agihaongagga

#

i dont get it
i just dont understand
why does this not work?

sour fulcrum
marble hemlock
#

im not seeing it i dont think

slender nymph
# marble hemlock agihaongagga

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.

polar acorn
marble hemlock
#
  • ?
#

right right

#

yeah its + notlikethis

naive pawn
#

-# fyi, it's not + in every language :)

marble hemlock
#

i got so used to using , and + interchangeably on python it didnt even click in my head it would be looking for another parameter

naive pawn
#

wdym, they aren't interchangable in python

marble hemlock
#

i cant tell if thats me being stupid or me being lucky then

#

my teacher never seemed concerned

naive pawn
#

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?

marble hemlock
#

specifically print

naive pawn
#

yeah print(a, b) would be like print(str(a) + sep + str(b))

#

but it's still not the same

wintry quarry
high summit
#

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

wintry quarry
#

Do you see your logs?

high summit
#

this is as i hold down left click

wintry quarry
#

Ok good

#

Also btw multiplying Time.deltaTime in there is incorrect

high summit
#

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...

▶ Play video
#

this is what i followed

wintry quarry
#

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

high summit
#

The script is on the object itself

#

that doesnt matter right?

brave compass
#

Maybe something else is changing the rotation of the object, like an animation.

high summit
#

Nah its just uh

#

one sec

#

an object attached to player camera view

#

so its infront of your face

wintry quarry
high summit
#

The object highlighted in the picture above

#

the medicine bottle

wintry quarry
#

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

high summit
#

and its kinda just twitching out, when i hold click and drag around

wintry quarry
high summit
#

Just working on that now

wintry quarry
#

(and when you do, you should reduce the rotation speed as well)

high summit
#

My unity decided to poop itself, 'Reloading domain' 1 min 30 seconds after saving that script

#

fml

high summit
#

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

wintry quarry
high summit
#

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

wintry quarry
#

how is that object positioned in front of your face

high summit
#

I have cursor locked

#

lol

#

That's going to be it isnt it

wintry quarry
#

Realisticlally you should be using mouse delta insteasd of position anyway

#

but yea

odd remnant
#

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?

wintry quarry
high summit
#

I would prefer to have the cursor invisible yeah

wintry quarry
high summit
#

am i not already using mouse delta?

odd remnant
wintry quarry
# high summit

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;```
wintry quarry
#

but yes, it can.

odd remnant
high summit
#

It's pivot is in it's middle, just checked

wintry quarry
#

how did you check

high summit
wintry quarry
#

you cut off important parts of this screenshot

#

Is your tool handle position set to Pivot, or Center?

high summit
#

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

cosmic quail
high summit
#

how does one change the pivot point of this 'none table version'

wintry quarry
#

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

high summit
#

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

final forge
#

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?

high summit
#

It's still wonky apparently, strange

#

Nvm I think I see what went wrong

jovial knoll
#

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

jovial knoll
odd remnant
high summit
#

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

final forge
#

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

naive pawn
# jovial knoll wdym?

don't post the same question across multiple channels
post in the correct place, once

final forge
#

or will they only stop when I disable the gameobject itself

naive pawn
naive pawn
jovial knoll
#

thanks @naive pawn

naive pawn
round mirage
#

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);
    }
}```
naive pawn
round mirage
#

oh

naive pawn
#

so every frame, you schedule a new one to spawn with a delay

round mirage
#

ok i see so i should call the coroutine inside the coroutine ?

naive pawn
#

i mean you could, but that wouldn't be very readable

round mirage
#

so what should i have to do ?

naive pawn
#

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 a while loop to keep doing the loop:
    • use WaitForSeconds with a random wait time
    • spawn
    • repeat
round mirage
# naive pawn you basically have 2 things operating over time here, the update loop and the `W...

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());
    }```
inland temple
#

Where can i ask for a good tree pack?

wintry quarry
naive pawn
naive pawn
#

and don't crosspost

odd remnant
#

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?

round mirage
#
    {
        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);
        }
    }```
naive pawn
#

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

odd remnant
#

Clamp basically limits the maximum value, to a value of my choosing, right?

#

(and minimum value)

naive pawn
#

yes

#

to limit just the max/min, that would be Min/Max, respectively

odd remnant
#

Got it. I'll take a look, thanks!

odd remnant
#

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.

naive pawn
#

just taking the delta of the mouse

odd remnant
#

When you say "virtual cursor" is that a Unity concept? Or do you mean a GameObject that works like a virtual cursor?

naive pawn
#

the latter

#

though maybe there's a version of the former im not aware of

odd remnant
#

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?

naive pawn
#

(though for the latter i don't think you'd necessarily need a separate gameobject, just a position could suffice)

odd remnant
#

Right.

naive pawn
odd remnant
# naive pawn well, im confused about what you mean here > if the mouse is outside the RectTra...

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. 🙂 )

naive pawn
#

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)

odd remnant
#

Yes!

#

Absolutely.

naive pawn
#

so if you move the mouse diagonally, you'd still be able to move in the direction not bounded by the screen edge

odd remnant
#

Right! Absolutely.

#

Yeah sorry, that was included in the blahblahblah.

#

I mean, how could you not understand that? 😉

naive pawn
#

ah, ok. wasn't sure what that entailed lol

odd remnant
#

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.

frigid sequoia
odd remnant
#

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?

naive pawn
warped sierra
#

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.

eager blade
#

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?

rich adder
wintry quarry
eager blade
frigid sequoia
#

I just use prints with the type of warning it is lol in like "Invoking object that does not exist!" or something like that

odd remnant
#

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? **

naive pawn
#

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)

odd remnant
naive pawn
#

basically, yes

odd remnant
#

Ok, that's awesome.

naive pawn
#

it's why the public static Instance is part of the singleton pattern

wintry quarry
#

A large draw of using SIngletons is just to be able to use a static accessor property. Use that.

odd remnant
#

So next question, which is a precursor to this one: Is it "best practice" for GameInput to be a singleton?

#

I assumed so.

naive pawn
#

needs more context to really answer

wintry quarry
odd remnant
#

Because ultimately, there's only one of them (per player, but we'll get to that)

wintry quarry
#

It's not really clear what "GameInput" actually does

naive pawn
#

the concept of a singleton is that a single entity exists throughout the lifetime of the runtime, and that it's accessible whenever/wherever

odd remnant
naive pawn
wintry quarry
odd remnant
#

So then - that's my reason why the class doesn't know what GameInput is. And I'm gonna make GameInput NOT a singleton.. 😂

naive pawn
#

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?

odd remnant
naive pawn
wintry quarry
odd remnant
wintry quarry
#

or just the instance of the actions asset itself

odd remnant
#

So I could instantiate the objects on equipping the item. And destroy them when unequipping them. Absolutely.

odd remnant
# wintry quarry or just the instance of the actions asset itself

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);
}`

naive pawn
wintry quarry
odd remnant
wintry quarry
#

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
frigid sequoia
naive pawn
# odd remnant This interests me. What would that entail?

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

naive pawn
odd remnant
naive pawn
#

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

frigid sequoia
naive pawn
#

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)

odd remnant
# wintry quarry if you just did: ```cs public InputSystem_Actions Actions => inputSystemActions;...

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.

frigid sequoia
#

Is there... a component pooling?

naive pawn
#

you can't

naive pawn
#

i don't know how that'd even work tbh, since you can't like AddComponent a component instance

frigid sequoia
#

I guess you could technically have the components on pooled objects, but seems pretty convoluted

naive pawn
#

in general you try to design stuff to not require unnecessary garbage

naive pawn
ripe shard
grand snow
#

you can still use the main component as the reference but enable/disable the gameobject

odd remnant
#

@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?)

grand snow
#

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

grand snow
odd remnant
#

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?

grand snow
#

yes but ugui may already cull and not draw a fully transparent Image but yea if its not being used it can be removed

odd remnant
#

Ok sweet.

grand snow
#

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

odd remnant
#

Is that happening every frame?

#

(Drawing it to the screen, effectively)

grand snow
#

well yea it will draw each frame but mesh recalculation/re creation cpu side is only when things change

grand snow
odd remnant
#

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?

hexed terrace
#

that should be a separate class

odd remnant
#

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.

frigid sequoia
#

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)

odd remnant
frigid sequoia
#

Is basically a supersimple store file for basic info, nothing big or delicate should be saved there

eternal needle
#

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

frigid sequoia
#

I would say it is fine to use for stuff like the basic config settings, it's alright

odd remnant
#

How does PlayerPrefs "work" though. Does it get saved on the client's computer? Or is it only used within Unity development?

eternal needle
#

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

odd remnant
#

Ok sweet. Thanks!

eternal needle
#

Still wouldnt bother using it. theres really just no point if you're going to be writing to file for other reasons

rich adder
#

PlayerPrefs pretty good for saving things like a login session authtokens

whole osprey
#

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.

queen adder
#

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?

wintry quarry
#

Look at the eyeballs in the left margin of the hierarchy window

queen adder
queen adder
queen adder
#

I didn't have these sorts of issues on the Windows version of Unity

polar acorn
#

Change this to "Pivot", then you'll see the gizmo where the object actually is

#

Make sure it's not just somewhere else

queen adder
hexed hare
#

Anyone have any simple 3d game ideas, but could become really crazy with some tweaks?

slender nymph
#

this is a code channel

odd remnant
#

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?

ripe shard
odd remnant
#

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.

ripe shard
#

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

odd remnant
earnest wind
#

Hello! What would be the best way to load a lot of photos from a folder?

earnest wind
#

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)));
            }
ripe shard
#

but its not the ultimate fast and efficient way (which is annoyingly complicated)

earnest wind
ripe shard
earnest wind
#

oh ok

ripe shard
#

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.

odd remnant
#

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.

earnest wind
#

wait while playing the game??? wdym by changing the default transform???

odd remnant
#

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.

earnest wind
odd remnant
#

Yeah. Alright! Thanks!

buoyant schooner
#

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();
    }```
buoyant schooner
rich adder
buoyant schooner
#

ah okay! I see

#

Does this mean I have to store the coroutine in a variable ?

rich adder
#

you can but don't have to if you just write it like above

#

yield return StartCoroutine ( AskInitialQuestions()) also works

#

both return Coroutine