#šŸ’»ā”ƒcode-beginner

1 messages Ā· Page 26 of 1

timber tide
#

I can understand what you're coming from, but prefabs and SOs are two different concepts, with prefabs being a saved set of gameobjects while SOs are templates for data. Both can be used interchangeably with each other.

subtle folio
#

If i understand correctly, say i make a SO of a bird, and make prefabs of different bird species based on the bird SO?

timber tide
#

It depends how exactly you want to design it, but usually you can just use a single prefab and have a collection of SOs for species.

subtle folio
#

I think i got the gist of it. Tysm

timber tide
#

It's a simple implementation idea assuming that the species prefab (components) doesn't change at all. Basically, you just load the data from the SOs for what type of species it should be and then populate it from them.

timber tide
# subtle folio I think i got the gist of it. Tysm

You can also make prefab variants, basically using that one specific prefab and overriding some values for when you do want to just input some data yourself. This idea works great for working on the scene, while the other idea is ideally for instantiating them directly with the SO.

#

There's a lot of ways about it.

pliant bridge
#

whats the best way to make a 2d character check if its next to a wall?
most tutorials out there teaches how to use ray casts, overlaps circle and stuff but they always have blind spots where it wont check and covering them manually isnt very ideal, where/how can I learn the best way to do that?

timber tide
#

Overlap shouldnt have blindspots

nocturne parcel
#

If so, there are some tutorials out there dealing with this

#

But if it's for checking stuff, if shouldn't have blind spots

ruby elk
#

Quick question for one of y'all, I made 0 changes to a script between yesterday and today and now the script is greyed out for all objects its on in the inspector. Does anyone have any ideas what that reason could be? I'm posting the inspector with a greyed out script vs non greyed. The code too. I'm sure the code is most likely idiotic since its essentially a single line but thats what (used to) works for me so I didn't want to change it. I will also post the code that is giving the error saying the greyed out script doesnt exist.

#

This was literally working yesterday but not today.

teal viper
#

Or the class name

ruby elk
#

SwordDamage. Always

teal viper
#

Are the 2 components on the first screenshot supposed to be "before vs now"? Or did I misunderstand?

ruby elk
#

No no, those were just on the same inspector of a sorta what a working one looks like (movement) vs not

#

And frankly I don't know where the checkmark went on the Movement script but I'm not too worried about that

teal viper
#

Because you said "I'm posting the inspector with a greyed out script vs non greyed out", so I thought it was before - after...

cosmic dagger
ruby elk
#

Yeah I worded it horribly

keen dew
#

This says both SwordScript and SwordMovement. That can't happen unless you've renamed the class or file

#

I suggest you just remove the scripts from the object and re-add them

ruby elk
#

Oh I just noticed that. I don't know why it did that

cosmic dagger
#

The SwordDamage does not show correctly. Rename the script and file name of SwordMovement to be the same . . .

ruby elk
#

Damage and Movement are different scripts

cosmic dagger
#

I know . . .

teal viper
#

Try reading the components. If the issue persists, share the whole script as well as a screenshot of the file name.

cosmic dagger
#

Make sure Movement has the same file name and class name . . .

ruby elk
#

Oh gotcha. Yes they are the same

cosmic dagger
#

Then drag the Damage script on the GameObject and see if it appears correctly . . .

ruby elk
#

Once again, Unity loves to do its own thing and managed to rename the class...

tacit grotto
#

I have an error on every rand.Next(), how do I fix it?

SpriteRenderer Sprite;
class Random;
Random rand = new Random();

void Start()
{
  Sprite = GetComponentInChildren<SpriteRenderer>();
  Sprite.color = new Color(rand.Next(100, 201) / 255, rand.Next(100, 201) / 255, rand.Next(100, 201) / 255);
}
cosmic dagger
tacit grotto
#

I don't have my computer on me, I will be able to tell after 30mins

ruby elk
#

Still getting an error when trying to now put SwordDamage onto the object. I'll put SS of the codes, filenames, and error of course, for both scripts.

#

And nothing on the console

keen dew
cosmic dagger
ruby elk
cosmic dagger
keen dew
#

Why aren't you using Unity's Random anyway

cosmic dagger
# ruby elk no

Didn't catch it earlier, but did you change any class or file names recently. That's what the problem seems like . . .

#

I'd re-open unity to see if it fixes itself . . .

ruby elk
#

If you look at the top of the code SS it has the filename and I did reopen it but I'll do it again just in case

tacit grotto
teal viper
ruby elk
#

Per Microsoft documentation on Random

tacit grotto
#

yes

keen dew
tacit grotto
#

Oh

#

makes sense

keen dew
#

If you really want to use C#'s own Random class then you need using System;

cosmic dagger
keen dew
#

but why use that when you have UnityEngine.Random

tacit grotto
#

Didn't know it existed.

#

Just a skill issue

cosmic dagger
#

New skill acquired . . .

keen dew
#

and the solution to the next issue is that you need either (float)Random.Range(100, 201) or Random.Range(100f, 200f) for the color to work properly

tacit grotto
#

Didn't know that you could get future telling skills by developing your coding skills enough.

ruby elk
#

Solved my issue by deleting the SwordDamage script, creating it new and retyping. Maybe cause I didn't have a Start()? Either way its fixed so thanks yall

teal viper
#

Start is unrelated.

ruby elk
#

I figured

cosmic dagger
ruby elk
#

Lucky enough it was my only code with 1 line of functionality

eternal falconBOT
#
šŸ’” IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)

• VS Code*
• JetBrains Rider
• Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

burnt vapor
#

Which is part of the problem, by the way.

ruby elk
#

Which was done when I initially installed Unity...

burnt vapor
ruby elk
#

I did. And All of those setting, extensions, packages, are already installed and up to date.

#

Either way it doesn't make much difference to me as I don't think VSC can tell me that I need to delete my code and recreate it.

burnt vapor
#

It's required you configure your editor properly before you ask a question because your editor is made to provide you with errors it can find, and it does not do that currently

ruby elk
#

Then why does my code autofill with unity recommendations?

#

(genuine question not trying to be rude)

burnt vapor
#

Either because it's partially configured or because it is a suggestion based on existing code

#

It's hard to tell with Visual Studio Code, and one of the reasons why you should not use it for Unity; setting it up is way more difficult than it should be

ruby elk
#

Most likely partially configured in that case.

burnt vapor
#

I suggest you see about using Visual Studio

ruby elk
#

I just installed it, will look into it more tomorrow.

topaz mortar
#

I have a Character gameobject that as a child has a healthbar gameobject
The character has a script Character that controls it's health
Do I add the healthbar as a variable (field?) in my character script and then drag it to link them?
Or do I use the GetComponent function?
Does it matter?

strong wren
timber tide
#

I usually expose fields for UI related stuff, but otherwise I'm usually just using GetComponent in their awake methods.

timber tide
#

It's just cleaner on the editor.

#

For the UI however, they are usually composed of a larger hierarchy, so it's preferable that you just tell it where the references are.

#

If it's something that you are going to be instantiating a lot of - like say some prefabs. That's a situation where you could consider just assigning it on the editor.

rough hill
#

Im using RecenterToTargetHeading with Cinemachine to recentre my camera. After I press the button the camera recenters as intended but after releasing the button my camera starts tilting downwards. What am I doing wrong?

north kiln
eternal falconBOT
#
šŸ’” IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)

• VS Code*
• JetBrains Rider
• Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

north kiln
topaz mortar
#

Is it ok to use the Find function when spawning a new monster so I can get it's healthbar in my combat script?
Or should I really avoid that function?

timber tide
topaz mortar
#

Ah nvm, apparently this works even if Slider is an object and not a component?
monsterHealthSlider = currentMonster.GetComponentInChildren<Slider>();

#

wait it is a component as well, so it's probably grabbing that

royal linden
#

why doesnt it work :~?

timber tide
timber tide
languid spire
royal linden
topaz mortar
#

Is there a way to make a [SerializeField] read only in the inspector?

vale blade
#

Say I have if (Foo() || Bar())
Bar() isn't called if Foo() is already true right?

vale blade
# languid spire yes, that is correct

looking to make this code a bit more concise, and I got a little bug where Y was not handled if X was already handled. Thought it was that, but thanks for confirming it.

Any suggestions as to make this more concise? I'm not sure if method extraction using ref even makes more sense here than just duplicating the calculation code?

private void Update()
{
    var screenMiddle = new Vector2(Screen.width / 2f, Screen.height / 2f);
    var mousePosScreen = Mouse.current.position.ReadValue();

    var deltaMouseToMiddle = (screenMiddle - mousePosScreen);
    var dirMouseToMiddle = deltaMouseToMiddle.normalized;

    var lookingAhead = HandleAxis(ref _transposer.m_ScreenX, deltaMouseToMiddle.x, screenMiddle.x, dirMouseToMiddle.x,
            _minPercentFromCenter.x, _sensitivity.x, _minScreenOffset.x, _maxScreenOffset.x);
    lookingAhead |= HandleAxis(ref _transposer.m_ScreenY, deltaMouseToMiddle.y, screenMiddle.y, -dirMouseToMiddle.y, 
            _minPercentFromCenter.y, _sensitivity.y, _minScreenOffset.y, _maxScreenOffset.y);

    if (lookingAhead) return;

    _transposer.m_ScreenX = Mathf.Lerp(_transposer.m_ScreenX, 0.5f, _smoothing);
    _transposer.m_ScreenY = Mathf.Lerp(_transposer.m_ScreenY, 0.5f, _smoothing);
}



private bool HandleAxis(ref float screenPosition, float deltaMouseToMiddle, float middle,
    float dirMouseToMiddle, float minPercentFromCenter,
    float sensitivity, float minScreenOffset, float maxScreenOffset)
{
    var percentFromCenter = Mathf.Abs(deltaMouseToMiddle) / middle; 
    if (percentFromCenter < minPercentFromCenter) return false;

    screenPosition = Mathf.Clamp(screenPosition + dirMouseToMiddle * sensitivity, minScreenOffset, maxScreenOffset);
    return true;
}
topaz mortar
#

Why is this not allowed?
float b = 1.3;

languid spire
#

because 1.3 is a double not a float

topaz mortar
#

isn't a double just a larger number float?

keen dew
#

Yes it is, that's why it's not allowed

lost hamlet
#

1.3f is a float however

languid spire
#

not quite but converting from double to float would require down casting and c# will not do that automatically

topaz mortar
#

but 1.3 is tiny? why is it not a float?

frosty hound
#

Because it's a double

#

A doesn't have to be a large number. It just can be a large number.

languid spire
#

the default type for numbers with decimals is double

lost hamlet
topaz mortar
#

hmm

lost hamlet
#

If it doesn't, it's a double

languid spire
topaz mortar
#

and then Mathf.Pow only works on floats, not doubles?

royal linden
topaz mortar
#

I must be doing something wrong

tacit estuary
keen dew
#

Why don't you just pass a float to it then

topaz mortar
#

yeah I guess that's easiest lol

ashen ferry
#

anyone knows if by the time SceneManager.activeSceneChanged is called is next scene loaded and I can call scripts there or not yet

topaz mortar
#

just trying to figure out if I'm doing something wrong or not

keen dew
#

well it doesn't even compile so

stiff kettle
#

yo idk if its a dumb question but i installed both unity and VS and i have configured it just like the tutorial said but now a few days later it stoped working( the autocomplt and stuff)
what am i missing here?

royal linden
#

can someone help me my pc like 3 fps and ive waited 14 mins for code to run

burnt vapor
royal linden
#

woudl be helpfull if you replied on how to cancel it

topaz mortar
#

just wondering why it's designed like that

topaz mortar
#

seems like by default it wants me to use Double, but then it forces me to use Float

burnt vapor
#

Unity compiling is not modifying your files, so you can cancel it with no risk

keen dew
languid spire
keen dew
#

The compiler can't make subjective evaluations like "this number is small so let's make it a float"

#

You have to tell it what data type to use

tacit estuary
formal bolt
#

hey im making a undertale fangame and how to make player can only in my square sprite?

burnt vapor
#

There's also very little reason to have a bigger number than what a 32-bit number allows. If you reach that limit you usually have the knowledge to extend it

formal bolt
#

is there any detection that is likey i can use it

topaz mortar
#

It was just very confusing to me that you have to add the f for a float, never ran into anything like that in PHP or JS

wintry quarry
keen dew
#

PHP and JS don't have separate data types for float and double

turbid glacier
#

yo my bro please add me as a friend

daring sinew
#

???

north kiln
#

!warn 613067723551014912 do not use this discord to randomly solicit friend requests

eternal falconBOT
#

dynoSuccess verletswing has been warned.

turbid glacier
#

@daring sinew hello I see you are making a 2D drag racing game, I am also in the process of doing so and there is 0 info online relating to helping me make this, unfortunately you have your dms and friend requests turned off so reply to this so we could hopefully talk about this thank you

north kiln
turbid glacier
north kiln
#
- • @ or reply to people not in the conversation. Use common sense here, please.
daring sinew
turbid glacier
#

And I just kinda typed really fast and pinged you my bad

lavish grotto
#

Just wanted to send a thanks for your suggestion ā¤ļø I got it working in about 1.5 hours. šŸ™‚

daring sinew
#

i see

turbid glacier
#

If you wanna talk here we can or DMs I don’t mind

#

how far have you gotten with your game

daring sinew
#

what are you capable of doing?

turbid glacier
#

ahhh so you’re pretty damn good at coding then

daring sinew
#

pretty new but eh

turbid glacier
#

but can’t figure out now to do grip

#

I tried adding mass or drag as online people have posted about that but it doesn’t really works

#

Yet to wrap my head around adding vehicles upgrades and mods

turbid glacier
daring sinew
turbid glacier
#

Yeah I saw you posting about that

finite star
turbid glacier
#

All this stuff is actually so confusing

daring sinew
#

indeed

turbid glacier
daring sinew
#

yes, but i dont get it

turbid glacier
daring sinew
#

yes

finite star
daring sinew
#

i have manual gears done

turbid glacier
#

very nice

#

I downloaded a 2d drag racing game on GitHub and they have car mods I think

#

Maybe I’ll try learn from that

daring sinew
turbid glacier
#

ohhhhh

#

I didn’t even think about using chatgbt that’s so smart

daring sinew
#

i just needed acceleration, not manual gears

daring sinew
#

i had to edit the code a lot to fix it

turbid glacier
#

Did chatgbt give you the gears and stuff

finite star
open apex
#

Hello! I am watching a video and when writing a code on visual studio https://prnt.sc/MK2bGBoEad6p this thing under the code comes up to help complete the code faster, but when I'm using visual studio I am not getting the same thing under the code, without it I am usually spelling something wrong https://prnt.sc/UXPkY_spgN7v . How can I fix this?

Lightshot

Captured with Lightshot

Lightshot

Captured with Lightshot

daring sinew
#

yes, but i could have done it myself already

eternal falconBOT
#
šŸ’” IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)

• VS Code*
• JetBrains Rider
• Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

turbid glacier
#

I have some amazing ideas for the game but the only thing holding me back is having the basic things coded

#

like driving and gears

open apex
turbid glacier
#

I can do the rest like scenes and etc etc

finite star
finite star
turbid glacier
#

maybe at some point we could great a group chat or something

daring sinew
#

could we 3 make a group or?

finite star
finite star
open apex
#

which one should I download

#

community?

north kiln
#

instead of downloading a different one. Though VS Community is better, you should download it via the Unity Hub if you want to use it

finite star
open apex
#

ok

turbid glacier
#

I’m leaving collage now to catch bud

#

Bus***

#

Will send my code when I’m back so you guys can examine it if you want

topaz mortar
#

Could/should I use a "ulong" instead of "double" for my experience system? numbers should all be integers

open apex
#

I'm bout to cry

#

😭

keen dew
topaz mortar
topaz mortar
#

I mean for now even a regular int is probably fine, but I dunno where my game might go after some updates

keen dew
#

Things like serializing can get annoying with the more exotic data types so you should really consider if you really need that big numbers or if you could change the design

topaz mortar
#

so long is probably better? or just keep double?

keen dew
#

int is better

#

But if that's not big enough then it doesn't matter if it's long or ulong

topaz mortar
#

Double sounds better for my experience system though

#

don't really care about the precision that much once the numbers get really big

#

float is probably fine too

ashen ferry
#

u can make ur own type like one int stands for how many max integer limits u reached and another as progress towards another limit lol then u can go into gazillion billion trillions or whatever

topaz mortar
#

I'd rather just keep it simple lol

ashen ferry
#

yea for the record my idea was stupid I found out theres BigInteger with seemingly no big catch to using it

topaz mortar
#

yeah saw that somewhere as well, but still too much for my current game

polar acorn
#

If you need ints bigger than max int, then you don't really have any other options

open apex
#

YES MR WHITE

#

I think I did it B)

#

does it save automatically?

#

is there a save button?

#

(the settings)

#

I did it šŸ˜Ž

#

Thanks for the help yall

gaunt snow
#

gayassblob I had the same problem and just came to check out the unity discord server and dam. That solved my problem lol

open apex
#

(probably cry 😭 )

gaunt snow
#

Lol yea I spent like 2 and a half hours just setting up unity cause of the file location. I could not get a project open lol. Eventually I learnt that I coulda just changed the whole file location in 5 mins.troll_funky

open apex
#

:DD

stone shoal
#

Is it possible to add 2 events on 1 line to a Button.OnClick.AddListener?

stone shoal
# rich adder wdym two events ?
                pauseMenuManager.forwardButtonPM.onClick.AddListener(() => StartAssigment("forward"));
                pauseMenuManager.forwardButtonPM.onClick.AddListener(() => SendText(forwardText));

This is what I got now, so then is it possible to combine it by adding the sendtext part to the first add listener

#

to make it more compact, less lines of codes

rich adder
stone shoal
summer stump
rich adder
#
        pauseMenuManager.onClick.AddListener(MyMethod);
    }
    void MyMethod()
    {
        StartAssigment("forward"));
        SendText(forwardText));
    }```
stone shoal
#

Or I would have half to remake half of my entire script

rich adder
#

how so?

summer stump
stone shoal
summer stump
stone shoal
#

Not the button name, a string which is being used for a switch case.

languid spire
rich adder
summer stump
obtuse oar
#

is there a method header comment assist like in IntelliJ with Java for VS with C#? in IntelliJ typing "/**" then pressing enter sets up a header comment for you

languid spire
#

use /// to create a summary comment

ashen ferry
#

is header like above everything for stuff like author

obtuse oar
languid spire
#
    /// <summary>
    /// 
    /// </summary>
    /// <param name="ok"></param>
    public Test(bool ok)
obtuse oar
#

this is what I mean

ashen ferry
#

just write /// as he said and it will make the template for u

obtuse oar
#

upon typing "/**" followed by enter it fills in all the params and return for you

polar acorn
swift crag
#

pretty sure that's JavaDoc-specific styling

obtuse oar
#

you just have to add the descriptions

ashen ferry
#

/// does that

swift crag
#

C# uses summary comments with XML markup

#

VS should be able to generate the comment for you based on the method.

polar acorn
#

Before typing ///:

swift crag
#

VSCode sure does.

polar acorn
#

After:

swift crag
#

I should really use these...

obtuse oar
#

hm maybe it's because most of my variables are declared outside the methods

swift crag
#

well, then, yes

#

those aren't parameters

#

so they won't appear in the list of parameters

polar acorn
#

Javadoc wouldn't get those either

swift crag
#

that wouldn't happen with --

#

yeah

obtuse oar
#

yeah sorry, complete dumb moment from me

#

ty for the "///" thing though, didnt know abt that

swift crag
#

You can also attach these to fields

#

or, more generally, any class member

#

it goes before the attribute, which results in an annoying ordering here

obtuse oar
#

yeah i find it much easier to reference those types of comments than to just spam inline ones

#

especially since they are readable from outside the class istelf if the method is used, at least that's how it works in IntelliJ with java

#

my experience is 90% IntelliJ with java so that's all i have to pull from

swift crag
#

hopefully, fields don't require a long diatribe to explain

obtuse oar
#

working within a team of people with very different styles of thinking is difficult, just trying to find ways to make communication on my methods easier

swift crag
#

Oh yeah, definitely work on filling out those summaries.

topaz mortar
#

More weird noob questions šŸ™‚
I have a Character script that tracks all my character stuff, like stats
There are several buttons that each increase a specific stat
Is it bad to set a reference on each button to my character script in the editor?

swift crag
swift crag
topaz mortar
#

nah just 3

swift crag
#

But I see nothing wrong with having a couple of buttons you have to manually reference.

obtuse oar
topaz mortar
#

I'm just not used to draggin stuff like you do in Unity and it doesn't make a lot of sense to me
To me it feels like I'm copying my character script on all the buttons

swift crag
#

You're referencing the Character component.

#

Whenever you drag something into a field in the inspector, you're referencing it

#

a reference isn't a copy; it's just saying "i use that object over there"

topaz mortar
#

Does it matter if I drag it from my Hierarchy or from my Project folder?

topaz mortar
swift crag
topaz mortar
#

yeah

swift crag
#

you're targeting whatever you drag in there

#

If you drag a script asset into it from the Project window, you're trying to target the script asset itself

#

which is not what you want

polar acorn
swift crag
#

You want to tell a specific instance of the player to increase their strength stat by 1

#

The script asset is used by Unity to track which script file is responsible for which component

topaz mortar
#

So I want to drag the script reference on my character onto them?

swift crag
#

Correct.

topaz mortar
#

cool, thx a lot šŸ™‚

swift crag
#

you would also not want to drag in a prefab with the character component on it

#

that would be less wrong (it'd indeed be the actual character component, not the script asset for the character component)

#

but you would be changing the stats of some prefab that doesn't even exist in your game

#

instead of, you know, your actual player's stats

pliant bridge
# nocturne parcel overlaps don't have blind spots tho, it literally goes around your whole charact...

i meant that its format is just not ideal at least for my character, i wanna check if its touching a wall and have a different checker for each side,
if I make the circle overlap too big i end up checking too far from where my character actually is, and too small makes some areas where my character may touch a wall where the circler overlap doesnt cover for not being big enough if you know what I mean,
i could make multiple overlaps to cover the height of my character but sounds a bit unpractical so I wanted to know if there was a more ideal way

summer stump
obtuse oar
#

is this how a summary should look?

    /// <summary>
    /// This method sets the numbers for the choices box the script is attatched to, additionally it makes sure that none of the numbers in the duplicates parameter are present in this choices box <para/>
    /// <paramref name="duplicates"/> -
    /// This parameter is the list of duplicates for the two other choices boxes in this column
    /// </summary>
    public void SetNums(List<int> duplicates) {
swift crag
#

you should just use <param> to list the params out

languid spire
swift crag
#

<paramref> is used to reference another parameter in your text

languid spire
obtuse oar
#

oh okay, i just let it autofill the "paramref" thing, was an option after typing "pa" lol

swift crag
#

The entire thing should be auto-generated for you after doing ///

obtuse oar
#

it did not auto generate the first time, that's odd

#

worked this time shrug

#

Should I put summaries on classes as well?

swift crag
#

I suppose it's nice to explain why something exists.

#

You should talk with your team about what they would find useful

pliant bridge
verbal dome
obtuse oar
#

goin through and commenting made me realize how inefficient this method looks, any ideas on improving this?
overall goal of the method, which is on a button, determine if the button is an up button or a down button. Then just adding functionality to have the numbers roll over from 0-9 since this is for incrementing a single digit box

    private void OnMouseDown() {
        if (Up) {
            if (selection_Box_Controller.currNum < 9) {
                selection_Box_Text.text = (++selection_Box_Controller.currNum).ToString();
            } else {
                selection_Box_Controller.currNum = 0;
                selection_Box_Text.text = selection_Box_Controller.currNum.ToString();
            }
        } else {
            if (selection_Box_Controller.currNum > 0) {
                selection_Box_Text.text = (--selection_Box_Controller.currNum).ToString();
            } else {
                selection_Box_Controller.currNum = 9;
                selection_Box_Text.text = selection_Box_Controller.currNum.ToString();
            }
        }
        selection_Box_Controller.CheckNum();
    }
polar acorn
obtuse oar
#

would that work for negatives?

polar acorn
#

I believe so, but I've just rememberd C# doesn't actually have modulo, it has remainder so let me double check

obtuse oar
#

that's a smart way to go about it though, that didnt even cross my mind lol

polar acorn
#

No, it does not. So you'd do (x + 10) % 10 to un-negative it

obtuse oar
#

gotcha, thanks

final kestrel
#
 private void Move()
 {
     Vector3 forward = transform.forward;
     float currentYVel = _rb.velocity.y;
     Vector3 newVelocity = transform.forward * _moveSpeed;
     newVelocity.y = currentYVel;
     _rb.velocity = newVelocity;
     //_rb.velocity = transform.forward * _moveSpeed;
 }

I am kind of confused how this method works. Can someone explain please?

polar acorn
final kestrel
#

The part why we play on the y velocity

polar acorn
#

Otherwise it'd become 0

final kestrel
#

float currentYVel = _rb.velocity.y; this is where we store the previous velocity then?

final kestrel
#

Why then we Vector3 newVelocity = transform.forward * _moveSpeed; do this

#

what is the point of setting a new velocity?

polar acorn
#

...to set the velocity

#

If you want to set the velocity to a vector, that vector needs to exist

final kestrel
#

hmm

#

Sorry I just got confused because we use = lots

#

Thanks for the explanation

polar acorn
summer stump
final kestrel
#

ah yes I know. It just felt overwhelming assigning variables that much.

final kestrel
#

I didnt have to make them local variables right?

twilit trail
#
public class PlayerPreview : NetworkBehaviour
{
    private NetworkVariable<int> skinColor = new NetworkVariable<int>(3, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
    private NetworkVariable<int> eyeColor = new NetworkVariable<int>(0, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
    private NetworkVariable<int> hairColor = new NetworkVariable<int>(0, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
    private NetworkVariable<int> hairStyle = new NetworkVariable<int>(0, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
    private NetworkVariable<int> outfit = new NetworkVariable<int>(0, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);

    [SerializeField] private Image skinImage;
    [SerializeField] private Image eyeImage;
    [SerializeField] private Image hairImage;
    [SerializeField] private PaperDollImage hairDoll;
    [SerializeField] private PaperDollImage outfitDoll;
    [SerializeField] private PlayerTexturesScriptableObject textures;

    public override void OnNetworkSpawn()
    {
        skinColor.OnValueChanged += SetSkin;
        eyeColor.OnValueChanged += SetEyes;
        hairColor.OnValueChanged += SetHairColor;
        hairStyle.OnValueChanged += SetHairStyle;
        outfit.OnValueChanged += SetOutfit;
    }

    public void NextSkin()
    {
        skinColor.Value = (skinColor.Value == 16) ? 0 : (skinColor.Value + 1);
    }
    public void PrevSkin()
    {
        skinColor.Value = (skinColor.Value == 0) ? 16 : (skinColor.Value - 1);
    }
    public void SetSkin(int previous, int current)
    {
        Material mat = skinImage.material;
        mat.SetFloat("_Current_Palette", (float)current);
    }
...```

when I set material properties like this it affects all instances of the prefab. i want it to only affect the calling instance instead. how do i make the material unique?
summer stump
#

Since they are only used right there, correct?

final kestrel
#

Yes that is correct

#

Damn you guys are cool

summer stump
final kestrel
#

Thanks a lot šŸ˜„

swift crag
#

You can then assign that copy into the material property

mild mortar
#

I'm brand new and trying to figure out how to do referencing properly

Wondering if I can get some help?

Essentially, I have a moving platform and a player character that has an empty object at it's feet I use to detect the ground.

I want to add a script to the groundcheck to see if the object it is colliding with has the tag "MovingBlock", and if it does, to then add the blocks velocity or such to the player character's

Because atm, my character just slides off the block if I put him on one

#

This is the start I have at the moment

void OnCollisionEnter(Collision collision)
    {
        if(collision.gameObject.name == "Ground Check" &&)
        {
            // Add this object's velocity to player
            


            
        }
    }
polar acorn
twilit trail
# swift crag You can then assign that copy into the `material` property

thank you! so as a quick test i did this and it seemed to work:

   public void SetSkin(int previous, int current)
    {
        Material mat = Instantiate<Material>(skinImage.material);
        mat.SetFloat("_Current_Palette", (float)current);
        skinImage.material = mat;
    }

my concern is i'm creating a new material with every change and I assume that is wasteful af. i assume better practice is to give each prefab a unique material at the start of the scene then set them how i was before?

mild mortar
swift crag
#

e.g. do it in Awake

twilit trail
#

got it thanks!

sand stump
#

Hey

junior mica
#

Hello, I am confused:
When I perform 'Physics2D.IgnoreCollision(object 1.GetComponent<CompositeCollider2D>(),object 2.GetComponent<CompositeCollider2D>(), true);' collisions always occur.
However, the same problem exists if I enter rather 'BoxCollider2D' or any other Collider2D.
Thus, only 'CompositeCollider2D' to the problem, I can however not use anything other than 'CompositeCollider2D'.
Do you have an idea?

mild mortar
# polar acorn Currently, you're checking if this object is colliding with an object named "Gro...
    void OnCollisionEnter(Collision collision)
    {
        if(collision.gameObject.CompareTag("MovingBlock"))
        {
            // Add this object's velocity to player

So I have the player character named "Player"
The empty object called "Ground Check" at Player's feet
And a bunch of platforms where I have made one specifically, move around and given it the tag "MovingBlock"

I want "Ground Check" to detect the tag, then copy the movement of the block and add it to the Player so that they don't slip off and can just stand still

polar acorn
sand stump
#

Do yall know that in the 2d pokemon games you can tap any direction slightly just to change the direction the player is facing wihtout walking?

how can i implement that into my player code?

using System.Collections;
using UnityEngine;

public class Player_Control : MonoBehaviour
{
public float MovementS;
public bool MoveIsTrue;
public Vector2 input;
private Animator animator;
public LayerMask SolidObjLayer;
public LayerMask InteractableLayer;
private void Awake()
{
animator = GetComponent<Animator>();
}

void Update()
{
    if (!MoveIsTrue)
    {
        input.x = Input.GetAxisRaw("Horizontal");
        input.y = Input.GetAxisRaw("Vertical");

        if (input.x != 0) input.y = 0;

        if (input != Vector2.zero)
        {
            var PlayerPos = transform.position;
            animator.SetFloat("MoveX", input.x);
            animator.SetFloat("MoveY", input.y);

            PlayerPos.x += input.x;
            PlayerPos.y += input.y;

            if (IsWalkable(PlayerPos))
            {
                StartCoroutine(Move(PlayerPos));
                MoveIsTrue = true;
            }
        }
    }
    animator.SetBool("MoveIsTrue", MoveIsTrue);
}

IEnumerator Move(Vector3 PlayerPos)
{
    while ((PlayerPos - transform.position).sqrMagnitude > Mathf.Epsilon)
    {
        transform.position = Vector3.MoveTowards(transform.position, PlayerPos, MovementS * Time.deltaTime);
        yield return null;
    }
    transform.position = PlayerPos;

    MoveIsTrue = false;
}

private bool IsWalkable(Vector3 PlayerPos)
{
    if (Physics2D.OverlapCircle(PlayerPos, 0.2f, SolidObjLayer | InteractableLayer) != null)
    {
        return false;
    }
    return true;
}

}

#

Sorry idk how to put code in discord

eternal falconBOT
#
Posting code

šŸ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

šŸ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

sand stump
mild mortar
polar acorn
#

if you're using rigidbodies, Rigidbody has a velocity property

sand stump
#
using System.Collections;
using UnityEngine;

public class Player_Control : MonoBehaviour
{
    public float MovementS;
    public bool MoveIsTrue;
    public Vector2 input;
    private Animator animator;
    public LayerMask SolidObjLayer;
    public LayerMask InteractableLayer;
    private void Awake()
    {
        animator = GetComponent<Animator>();
    }

    void Update()
    {
        if (!MoveIsTrue)
        {
            input.x = Input.GetAxisRaw("Horizontal");
            input.y = Input.GetAxisRaw("Vertical");

            if (input.x != 0) input.y = 0;

            if (input != Vector2.zero)
            {
                var PlayerPos = transform.position;
                animator.SetFloat("MoveX", input.x);
                animator.SetFloat("MoveY", input.y);

                PlayerPos.x += input.x;
                PlayerPos.y += input.y;

                if (IsWalkable(PlayerPos))
                {
                    StartCoroutine(Move(PlayerPos));
                    MoveIsTrue = true;
                }
            }
        }
        animator.SetBool("MoveIsTrue", MoveIsTrue);
    }

    IEnumerator Move(Vector3 PlayerPos)
    {
        while ((PlayerPos - transform.position).sqrMagnitude > Mathf.Epsilon)
        {
            transform.position = Vector3.MoveTowards(transform.position, PlayerPos, MovementS * Time.deltaTime);
            yield return null;
        }
        transform.position = PlayerPos;

        MoveIsTrue = false;
    }

    private bool IsWalkable(Vector3 PlayerPos)
    {
        if (Physics2D.OverlapCircle(PlayerPos, 0.2f, SolidObjLayer | InteractableLayer) != null)
        {
            return false;
        }
        return true;
    }
}
```cs
junior mica
sand stump
#

Do yall know that in the 2d pokemon games you can tap any direction slightly just to change the direction the player is facing wihtout walking?

how can i implement that into my player code?

mild mortar
# polar acorn GameObjects don't have any property named velocity. What "velocity" means depend...

Oh right

So basically, the block is just moving between two waypoint objects that I created. So it is using transform.position and Vector3.MoveTowards

This is the waypoint code I have on the block

public class WaypointFollow : MonoBehaviour
{
    [SerializeField] GameObject[] waypoints;
    int currentWaypointIndex = 0;

    [SerializeField] float speed = 1;

    // Update is called once per frame
    void Update()
    {
        if (Vector3.Distance(transform.position, waypoints[currentWaypointIndex].transform.position) < .1f)
        {
            currentWaypointIndex ++;
            if (currentWaypointIndex >= waypoints.Length)
            {
                currentWaypointIndex = 0;
            }
        }

        transform.position = Vector3.MoveTowards(transform.position, waypoints[currentWaypointIndex].transform.position, speed * Time.deltaTime);
    }
}
frozen mantle
sand stump
frozen mantle
#

Do you have a action map in your project?

#

@sand stump

#

Or input map, forgot what it's called

sand stump
#

Sorry but idk

#

Im really new to this all, sorry for any dumb questions lmao

polar acorn
final kestrel
#

Does an object with rigidbody that is standing still on the ground has a negative y velocity? because of the gravity?

frozen mantle
polar acorn
frozen mantle
final kestrel
#

hmm okay. is it common practice to store the y velocity before doing something to preserve it?

swift crag
#

You would have to actively choose to use the new input system.

#

so, by default, you will be using the old one.

mild mortar
frozen mantle
# sand stump No

Okay, so what I would personally recommend is to use the input system, you do that by installing the package for it in your package manager

frozen mantle
# sand stump ok , imma install that one sec

But, if you don't wanna do that for whatever reason, basically what you want is to make the first like, 0.1 second of holding a movement key just change the players direction, and if they hold that key, they will start moving

polar acorn
swift crag
#

I'm not sure I'd leap straight for "learn the new input system"

sand stump
#

So wheres the package manager?

frozen mantle
#

I would go and look at some docs on how you cna do that

#

I gotta go back to work so you'll have to ask someone else, apologies

swift crag
#

All you need to do here is to add a slight delay before your movement input actually causes the player to start moving.

sand stump
swift crag
#
void Update() {
#

bah

#

ipad keyboard moment

#

actually, I won't write out code just yet.

sand stump
#

LoL relatable

swift crag
#

The big idea is:

sand stump
swift crag
#

i think my shift key isn't working..

#

If the move input is zero, reset a counter to a small value (maybe 0.2)

#

If the move input is non-zero, subtract Time.deltaTime from the counter

#

Use the move input to rotate the player

#

If the counter is less than or equal to zero, use the move input to move the player.

swift crag
#

Do you move on a grid in this game?

#

like in old Pokemon games

sand stump
swift crag
#

In that case, you probably want to move instantly if you're already facing the right direction

swift crag
#

Perhaps by setting the counter to 0 if, on the first frame that you try to move, you're already facing the direction you want to move

sand stump
#

Ok, ill search on how to do that

spring coral
#

is there any way that i can reference a scriptableobject and make adjustments to one of its fields without changing the base asset, similar to a prefab?

verbal dome
spring coral
#

this is all done at editor time

verbal dome
#

Dont matter

polar acorn
#

Or use ScriptableObject.CreateInstance<___> with whatever type

swift crag
#

are you trying to make a new asset?

verbal dome
#

Just remember to DestroyImmediate it in OnDisable or something, so it doesnt leak

polar acorn
#

if you don't want it to clone an existing one and instead be whole-cloth new

spring coral
#

i want to make the adjustments at editor time though, so how would i serialize and save these changes so it takes affect at runtime?

verbal dome
#

You want to save it to a diffeeent asset?

spring coral
#

think of how you can drop prefabs into a scene but modify some of the fields without changing the values on the base prefab

#

sort of like that

#

dont know if its possible with SOs

verbal dome
#

The instantiated SO needs to be saved somewhere

#

Not sure if it gets serialized if you put it on a field on a gameobject, maybe try that

spring coral
#

hmm ill have to experiment then

verbal dome
#

Instantiate, modify, assign to a serialized field

spring coral
#

at least with the way that i know how prefabs work is that if you reference a prefab then make modifications to that prefab via inspector, it serializes ONLY the changes and fetches all the other values from the base prefab

verbal dome
spring coral
#

ahh alright

verbal dome
#

It would be dope though

spring coral
#

yeah thats pretty much what i was wondering since ive never seen that behaviour

#

yeah for sure

#

maybe ill work on a plugin for that in the future

verbal dome
#

The closest I have seen to that is the Volume framework

#

Where you can override or not override parameters

spring coral
#

havent seen it before

verbal dome
#

Post processing volume, etc

#

Uses that

spring coral
#

huh, ive never seen it, is it on URP?

#

that workflow i mean, ive used those assets ofc

verbal dome
#

Volume profiles is what I mean

#

The page seems to be missing on the URP doc šŸ¤”

spring coral
verbal dome
#

I might look into it myself too

spring coral
#

huh, cool

nova trout
#

hello, i want to start coding again, i updated my visual studio, but idk what to download now so i can edit / make C# scripts for unity. thanks for help

rich adder
#

this mf..

#

just ignores replies and crossposts

summer stump
rich adder
obtuse oar
#

is there any benefit to a switch statement vs if else when there's only two options? like for a single bool

buoyant knot
#

no

#

i’ll do that only if I’m expecting my if to become a big switch case in future

#

How does Rigidbody.MovePosition work? Does it teleport my rigidbody there with all the colliders? Does it stop my rigidbody early? does it move other things out of the way etc?

buoyant knot
#

all i see is that moveposition normally moves things smoothly

rich adder
#

2D or 3D?

buoyant knot
#

but it’s hard for me to see if colliders are getting moved as a result of MovePosition, or afterwards in physics simulation step

#

2D

rich adder
buoyant knot
#

I’m trying to figure out how different steps will work together in terms of script execution order

#

i have a motor which moves a platform, and the platform moves an enemy. And these happen on different parts of a frame, so I want to understand how they affect each other’s calculations

#

my main issue right now is if the enemy falls onto platform while it is moving down, they don’t connect. He stutters in the air (like the platform’s collision held it at its old position), and platform keeps moving.

#

so it is super janky

#

make a prefab variant

buoyant knot
#

MovePosition

rich adder
#

made my red cube fall onto a white cube with MovePosition

buoyant knot
#

lift is parented to motor, and motor uses MovePosition

#

well, here is where it gets tricky: When the enemy is in contact with the lift, I move the enemy’s transform

rich adder
#

hmm already higher drop it moves weird

buoyant knot
#

I basically calculate how much the lift has moved since last frame, then transform.Translate by that amount.

#

RB.moveposition doesn’t work for me there

rich adder
#

Translate might be messing with the accuracy of positions of the rbs

buoyant knot
#

and the lift doesn’t have a defined velocity (since it is just moved by moveposition), so I can’t copy velocity differences over

ivory bobcat
buoyant knot
#

there is a lot of code. I’m sparing you the details

#

I have like 4 relevant scripts here, all of like 300 lines

ivory bobcat
#

We would only need to know the implementation of movements

buoyant knot
#

but it all comes down to a few critical lines at the core

ivory bobcat
#

Else we're guessing without being able to see what's actually happening

buoyant knot
#

enemy has a ReferenceFrameHandler component, with early execution order. ReferenceFrameHandler uses Transform.Translate to move the enemy by how much the lift has moved last frame. And it usually works really well

#

motor moves by MovePosition

#

Lift is parented to motor

#

i tried all sorts of things to set parents etc, joints, or rigidbody.MovePosition to couple the enemy motion, but nothing really worked. Only moving the transform worked.

#

idk maybe using synctransforms after using translate will work

#

i would love if there were just a joint that just sent movement of one object to another, while not contraining it

ivory bobcat
#

It would be some custom game physics and not necessarily Rigidbody/Kinematic physics.

swift crag
#

despite looking like separate blocks (because you have many statements that end in a break, and you indent them all), it's all one big block

#
        bool what = Random.value < 0.5f;
        
        switch (what)
        {
            case true:
                int x = 3;
                break;
            case false:
                int x = 3;
                break;
        }
#

This will cause a compile error because x is declared twice in the same block

languid spire
#

you can scope within a case to avoid that

swift crag
#
        bool what = Random.value < 0.5f;

        switch (what)
        {
            case true:
                {
                    int x = 3;
                    break;
                }
            case false:
                {
                    int x = 3;
                    break;
                }
        }

I like to do this nowadays.

#

Yep.

#

Block statement in each case. Horrific indentation, though.

#

I think I can configure that...

#

I use these to implement simple state machines.

obtuse oar
swift crag
#

newlines for braces is the default

#

I kinda flip-flop on this.

rich adder
ivory bobcat
#

The alternative if-statement would be: cs bool what = Random.value < 0.5f; if (what) int x = 3; else int x = 3;which can be much cleaner

#

Ignore obsolete stuff

swift crag
rich adder
swift crag
#

if you're not putting multiple cases together, they're pretty much just a roundabout way to write an if / else if / else if / ... sequence

ivory bobcat
swift crag
#

can you even allow fallthrough?

#

it's a compile error by default, at least

ivory bobcat
#

It's a niche case that isn't ever so useful - hackish.

swift crag
#

duff's device!

#

This leads to what the Jargon File calls "the most dramatic use yet seen of fall through in C".[5] C's default fall-through in case statements has long been one of its most controversial features; Duff himself said that "This code forms some sort of argument in that debate, but I'm not sure whether it's for or against."[5]

lol

ivory bobcat
#

It's formatting is quite pretty though but.. it's very much like a lookup table but with all of the code jumbo'd below - the case bodies can be scoped but each expression would still be processed like chained if statements.

buoyant knot
#

i changed the one line { setting immediately once I got visual studio. It drives me insane

somber wren
#

has anyone an idea of why those two object, at the exact same place but not in the same project has not the same coordonates ?

#

1st one is not bugged, 2nd is

short hazel
#

One of the two has a parent object

somber wren
#

both have

#

and both are at 0 0 0

short hazel
#

Inspector shows Local coordinates, always

somber wren
#

its the same prefab, same size

#

yeah i know

#

so yeah

#

im gonna cry

#

i've been on a bug since 3 days, and now i found the problem

#

my targets are misplaced for absolute no reason

#

but only on the inspector, on the scene it is at the right place. So when i play, it get misplaced.
And if i place them correctly on the inspector, but they show misplaced on the scene. They get right placed when i play

ivory bobcat
vapid igloo
#

Is this code right?

using System.Collections.Generic;
using UnityEngine;

namespace SojaExiles

{
    public class opencloseDoor : MonoBehaviour
    {

        public Animator openandclose;
        public bool open;
        public Transform Player;

        void Start()
        {
            open = false;
        }

        void OnMouseOver()
        {
            {
                if (Player)
                {
                    float dist = Vector3.Distance(Player.position, transform.position);
                    if (dist < 15)
                    {
                        if (open == false)
                        {
                            if (Input.GetMouseButtonDown(0))
                            {
                                StartCoroutine(opening());
                            }
                        }
                        else
                        {
                            if (open == true)
                            {
                                if (Input.GetMouseButtonDown(0))
                                {
                                    StartCoroutine(closing());
                                }
                            }

                        }

                    }
                }

            }

        }

        IEnumerator opening()
        {
            print("you are opening the door");
            openandclose.Play("Opening");
            open = true;
            yield return new WaitForSeconds(.5f);
        }

        IEnumerator closing()
        {
            print("you are closing the door");
            openandclose.Play("Closing");
            open = false;
            yield return new WaitForSeconds(.5f);
        }


    }
}```
somber wren
#

The bugged spider vs The not bugged spider :

vapid igloo
#

sorry for flood btw

somber wren
#

wdym right ?

vapid igloo
#

does it work

ivory bobcat
somber wren
cosmic dagger
# vapid igloo sorry for flood btw

np, use any of the sites from !code to copy/paste your code, save, then send us the link. it'll avoid the wall of code that scrolls up other ppls questions and responses . . .

eternal falconBOT
#
Posting code

šŸ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

šŸ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

short hazel
somber wren
#

but i setted them up just like in the first project

#

and yes it matters bc when i my spider moves, the positions are completely offset

#

what does pivot do ?

short hazel
#

Pivot / Local, two buttons

somber wren
#

hmm i see thanks

#

but doesnt change anything idk

vapid igloo
#

i cant add it for some reason

somber wren
#

i'm asking why my ik targets are in a position on the scene, but its not the same as in the inspector 😭

cosmic dagger
polar acorn
# vapid igloo

Make sure that there are no compile errors and that the file name and class name match

vapid igloo
polar acorn
somber wren
#

i see

#

thanks

cosmic dagger
vapid igloo
#

ohh the public class thing

#

kk

short hazel
#
public class Sample : MonoBehaviour
//           ^~~~~~ Class Name
dawn oracle
#

Any tips on where to start learning c# I have a decent experience in minecraft skript

eternal falconBOT
#

šŸ§‘ā€šŸ« Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/

vapid igloo
short hazel
#

Show both

polar acorn
ivory bobcat
polar acorn
short hazel
#

In one image, just to be sure

ivory bobcat
#

Previous error basically suggested that they did not match or there were compiler errors

short hazel
#

Well from what I'm seeing from earlier screenshots, the file name is Door.cs but the class name is openCloseDoor

#

So definitely not matching

vapid igloo
#

i changed it

#

now it matches

#

but now it just loops

#

idk why

ivory bobcat
#

Is this a different error?

vapid igloo
ivory bobcat
#

So problem resolved?

vapid igloo
#

when i start it loops

#

instead of me opening the door

polar acorn
vapid igloo
polar acorn
ivory bobcat
#

This doesn't look related to the previous error.

polar acorn
#

It tells you pretty clearly what to do, check the full text of it in the console

ivory bobcat
#

(or through code etc - preferably inspector if possible)

vapid igloo
ivory bobcat
#

Make sure to read and fix the error - including any other from the console tab.

vapid igloo
#

so i assign it with my animation ?

#

just loops the animation

#

now i need a animatorcontroller for the animator

#

which when i put the animation it loops

ivory bobcat
#

Best to follow a tutorial if you're not sure what you're doing.

timber sundial
#

Anyone able to help me with GUILayout.HorizontalSliders?

#

i have ```cs
GUILayout.Box("Columns: " + Mathf.Round(columns));
columns = GUILayout.HorizontalSlider(columns, 3.0f, maxColumns);

#

but my slider is still 1-5. columns is set to 1 and max columns is set to 15

zealous oxide
#

hey peeps, im trying to read an enumator from one script in another script and use its value (its a direction, Up, Down etc) to set the vector2 of the second script, but i cant figure out how to get it to work https://hastebin.com/share/ilesimolup.csharp

ashen ferry
#

change D into d u typed in there actual enum type also its private

zealous oxide
rich adder
polar acorn
swift crag
#

new Vector2.direction.normalized makes no sense.

#

This is trying to access a member named direction on Vector2, then trying to get normalized from that.

ashen ferry
#

wtf

swift crag
#

Perhaps you wanted to do this?

#

direction.normalized

#

This would access the normalized property from direction, which would be valid

zealous oxide
#

i know what i'd like to do but i'm not sure i can articulate it in c#

ashen ferry
#

how did u end up with that even

polar acorn
swift crag
polar acorn
swift crag
#

but it's an enumeration type

ashen ferry
#

AAA

swift crag
#

so you have a value from an enum type, and you want to create a Vector2 based on that value.

zealous oxide
polar acorn
polar acorn
# zealous oxide

Okay, so you want to get this field and then turn it into a vector

#

So you're going to need a switch statement

#

or a chain of ifs at least

swift crag
#
PlayerCombatEntity.Direction

this doesn't make much sense, partially because you didn't share PlayerCombatEntity

#

It looks like you've declared an enum named Direction in several different places

#

These are all completely unrelated types.

short hazel
#

Enumeration, btw. Enumerator is something else entirely!

#

Or enum, for shorts

swift crag
#

PlayerCombatEntity.Direction is the enum type itself. It is not a value.

#

Perhaps you wanted playerScript.direction .

wintry quarry
# zealous oxide
Quaternion.Euler(0, 0, 90 * (int)theDirection) * Vector3.up;``` is a cute way to do it.
#

if you rearrange that to Up, Right, Down, Left

#

or add Up = 0, Down = 2, Left = 3, Right = 1

ashen ferry
#

save lines of code lose lines on comments cause u gonna forget how that works kekW

timber tide
#

I'm making a little voxel editor and I was wondering what's the best way I should detect the faces of a voxel to append to. I was just thinking about detecting a point on the collider, but I'm not entirely sure of the method to grab the specific face of the voxel, maybe the idea is to create a voxel with a collider for each face?

wintry quarry
#

eh, one line.
You could also do

Up = 0,
Right = 90,
Down = 180,
Left = 270``` in your enum and directly use it
wintry quarry
#

with box colliders

timber tide
#

Oh right, yeah good idea

swift crag
#

an extension method might be enjoyable to use

#
public enum Direction
{
    Up,
    Right,
    Down,
    Left
}

public static class DirectionExtensionMethods
{
    public static Vector2 Vector(this Direction direction) => direction switch {
        Direction.Up => Vector2.up,
        Direction.Right => Vector2.right,
        Direction.Down => Vector2.down,
        Direction.Left => Vector2.left,
        _ => Vector2.zero
    };
}
#

then:

#
        Direction dir = Direction.Left;
        Vector2 vec = dir.Vector();
wintry quarry
#

another good option ā˜ļø

swift crag
#

if only you could do extension properties

#

an extension method lets you create new methods you can call on an existing type

wintry quarry
#

could also do the same as an implicit or explicit conversion operator

zealous oxide
#

hey Fen, thanks for this, im going to try applying this to my script, thank you for the advice everyone

swift crag
#

oh, that's a good idea

#

although, can you do that

wintry quarry
#

I think so?

swift crag
#

you can't put operators in the enum definition and you can't put an operator in a static class

#

(you can't put methods in the enum definition in general)

#

Anyway, getting back to the original code, there were several problems:

  • PlayerCombatEntity.Direction is just the enum type. playerScript.direction is a field of that type, which is what you wanted
  • You've declared an enum named Direction in several places. These are all unrelated types, even if they have the same name and the same values. You should just declare Direction once, and not nest it inside another type
  • new Vector2.direction.normalized is bogus syntax
  • new Vector2(direction) wouldn't work because C# has no clue how to construct a Vector2 from your enum.
  • direction.normalized wouldn't work because Direction is just an enum type, and it has no property named normalized
zealous oxide
#

this is my first time using enums

dry tendon
#

Hi everyone, do you think it would be better to use an invoke here to run the startTheGame function after the onPlayButtonClick function has executed? I think it would be better because it would eliminate a public variable and make the code more concise and easier to read. ```cs
public bool hasPlayButtonBeenClicked = false;
public void OnPlayButtonClick()
{
// Prepare canvas
mainMenuCanvas.SetActive(false);
getReadyCanvas.SetActive(true);

    // Click sound
    AudioManager.Instance.PlaySound(transitionSwooshSound);

    // Has play button been clicked = true
    hasPlayButtonBeenClicked = true;
}

void startTheGame()
{
    if (Input.GetMouseButtonDown(0) && hasPlayButtonBeenClicked == true)
    {
        getReadyCanvas.SetActive(false);
        PipesController.Instance.canSpawnPipes = true;
        PipesController.Instance.hasCollisioned = false;
        playerRb.bodyType = RigidbodyType2D.Dynamic;
        player.canPlayDieSound = true;
        player.canPlayJumpSound = true;

        AudioManager.Instance.PlaySound(jumpSound);
        playerRb.velocity = Vector2.zero;
        Vector2 fuerza = new Vector2(0f, player.impulse);
        playerRb.AddForce(fuerza, ForceMode2D.Impulse);

        hasPlayButtonBeenClicked = false;
    }
}```
swift crag
#

is it important that startTheGame does not run instantly?

dry tendon
#

Its the time it takes to change the ready screen to the play screen in a flappy bird, what do you think?

#

Its for a mobile game...

swift crag
#

I'd keep the "has been clicked" variable, though, so that you can't start the game 15 times

#

note that it doesn't need to be public here

dry tendon
swift crag
#

also, an important distinction: "public" and "serialized" are two separate ideas

#

the former means that other components can see the variable. the latter means it shows up in the inspector and gets saved in the scene

#

public variables are serialized and private variables aren't, by default

#

So if you were thinking that it's annoying to have that in the inspector, then that's not strictly because it's public -- it's because public variables are serialized by default.

dry tendon
#

i didnt have much clear the difference between both of them

swift crag
#

A non-public field can be serialized if you add [SerializeField] to it, and a public field can be non-serialized if you add [System.NonSerialized] to it

dry tendon
#

and in a few words, serialize, is to make it visible and editable on unity inspector, right?

swift crag
#

Something is "serialized" if it's saved, basically

#

that means it will show up in the inspector

dry tendon
#

And, one other thing, if for example I create a public var cs public int points = 5; on c# and later i change its value on unity inspector to 6, when i make the final build of the project, wich value will it take? what will happen with the other one?

swift crag
#

That's called a "field initializer". It provides an initial value for the field.

polar acorn
swift crag
#

This happens the instant that the object is created. Unity will then apply the serialized values.

#

So, for objects in the scene (or for prefabs), the value in the inspector is the value you will get.

#

points will be be 5 or 6 or whatever the initializer says until Unity applies the saved values

#

(and it does so immediately)

#

New instances will use the initializer's value, since there is no saved value at all

#

And if you hit "reset" on a component, you'll also get the initializer value

#

since the whole point of that Reset option is to clear the saved values

lone sable
#

I know I can build one but.

Does anyone have any good free assets that allow for easy debug menu creation? EG: Press F1, give yourself/spawn in items, all that jazz. I know I'd have to build the hooks into it, but yeah. Just curious if theres anything already out there.

swift crag
#

There are some assets for "dev consoles"

#

press tilde, noclip

dry tendon
lone sable
swift crag
#

So if you make that field private, or add [System.NonSerialized], then it won't show up in the inspector, and no value will be saved

#

so you'll always get whatever value the initializer sets

#

If you make it private, and then add [SerializeField], it will go back to having its value saved

civic rock
#

Hello all. I've had a problem that I hope somebody could help me with - I guess it's probably a beginner query since I'm trying to do something quite basic that, as I understand, should work, but just... Doesn't.

I'm trying to serialize a list as part of a MonoBehaviour:

private List<WeaponInfo> weapons;```
This list is read, but never modified or assigned, by the containing class; and no other class has access to it.

The `WeaponInfo` class is defined in a separate file as follows:
```[Serializable]
public class WeaponInfo
{
    [SerializeField] private int weaponID = 0;
    [SerializeField] private int groupID = 0;
    [SerializeField] private bool isAvailable = false;
    [SerializeField] private GameObject weapon = null;
}```
This omits some accessors for the sake of brevity.

However, what I'm observing is that, although I'm able to populate the list and WeaponInfo data as expected within the inspector, upon entering play mode, the list in memory is empty - although it still appears populated in the inspector. I've confirmed the list isn't being cleared anywhere in the code I've written, and nor is it being reassigned. The inspector continues to show what I expect (ie. the data I populated the list with), but debugging reveals the list to have no elements. I'm not using any custom editor or serialization code for this class.

Furthermore, if I add an additional list, and an array, purely for the sake of testing:
```public List<GameObject> gameObjects;
public GameObject[] gameObjects2;```
And then populate them via the inspector with data, these behave in the same way as the original list - that is, the inspector will appear populated, including on entering play mode, but the list and array will in fact be empty if I place a breakpoint and inspect them with my debugger. This will happen even if I try to populate an array of primitives, eg. `public int[] ints;`.

I imagine that there's some very simple mistake that I've made here - but I can't for the life of me think what it might be. Could anybody offer any insight?

(And apologies for such a long initial query, but I wanted to include as much relevant information as I could)
timber tide
#

This data is being set in the inspector?

#

Make sure you're not reinstantiating the list

civic rock
#

Yes - the list and the contents of WeaponInfo appear in the inspector, and I can edit them as expected. In the inspector, they remain populated when I enter play mode - but as soon as code that attempts to read them runs, the code will start logging errors because the list is unexpectedly empty. It's not being reinitialised or modified anywhere in the containing class, and there's no other class that has access to it (and it's not passed to another class's method either; it's strictly internal to the containing MonoBehaviour)

wintry quarry
#

can you show more of the code (especially the part that reads the list?) and where you set your breakpoints?

obsidian fern
#

Is a horizontal line a function?

wintry quarry
#

or whatever the height of the line is

#

lineHeight

obsidian fern
#

The line is on y=2

wintry quarry
#

then sure the function is f(x) = 2

obsidian fern
#

I am having hard time understanding because I thought a function had to be consistent because multiple y values equal different x values

swift crag
#

you are thinking of the mathematical definition of a function.

obsidian fern
#

Yes that's correct

wintry quarry
swift crag
#

but yes, that's still not a problem

#

a vertical line is impossible to define as a function of x

wintry quarry
#

in this case it happens that all outputs are 2, no matter the input

swift crag
#

but a horizontal line is fine.

polar acorn
swift crag
#

I suspect you are looking at the wrong instance, yes.

obsidian fern
#

Thanks a lot @wintry quarry and @swift crag

#

Good to see the same guys are here a year later.

#

I'm on math now. Had to put game dev on pause because I need sharper math skills for it

swift crag
#

i've never really thought about the formal definition of a function when working on a game

civic rock
# swift crag I suspect you are looking at the wrong instance, yes.

It looks like you're right - there were, somehow, two instances of the class on the same GameObject, one at the bottom of the components list and one somewhere in the middle where I hadn't noticed it (and I hadn't been looking for a second instance since the behaviour had DisallowMultipleComponent); I hadn't spotted this while debugging since my breakpoint was on an accessor, and thus only being triggered for the instance returned by GetComponent when the caller was initialised - which was the erroneous instance rather than the one I'd populated.

I'm not sure quite how the second got there - above several other components when it should have been the most recently added, and especially with DisallowMultipleComponent - but that was indeed the problem. Thanks.

swift crag
#

Clicking on an error in the console will take you to the offending component, if possible

#

That can help you find duplicates

royal linden
#

why is this under lined

summer stump
royal linden
#

?

summer stump
#

It doesn't know whether to use System.Random or UnityEngine.Random

#

Fully qualify it or write
using Random = UnityEngine.Random;

royal linden
#

oh

summer stump
#

Well wait. You don't have using System....

#

What does the error actually SAY?

#

What does your IDE tell you to do to fix it?

royal linden
summer stump
#

Oh I see it. Unity.Mathematics

eternal needle
#

the error is right there, its ambiguity between Unity.Mathematics.Random and UnityEngine.Random

royal linden
#

i fixed it ty

heady nimbus
#

Hey, dumb beginner question. Simple player movement code with rigidbody2d.velocity I'm getting a lot of sliding around when I release the direction button. I can get rid of it by increasing the drag, but then I get some weird issues with jumping. Suggestions?

https://hatebin.com/whqlitwrpy

light moss
summer stump
# royal linden i fixed it ty

Why do you even have Unity.Mathematics there? I would just remove that as the simplest fix, since you aren't using it there

But yeah, I guess you fixed it already

ivory bobcat
#

As is, you're not doing anything to velocity when the buttons aren't pressed.

#

Maybe have v.x = 0f on line 4

heady nimbus
ivory bobcat
heady nimbus
#

Ok that gives me the smooth stop I was looking for, thank you. I just need to work out carrying that velocity over into the jump, as now it loses all momentum on a jump

ivory bobcat
#

Maybe only apply the stop/deceleration if grounded

light moss
royal linden
#

this wont crash my pc will it

heady nimbus
ivory bobcat
royal linden
ivory bobcat
#

Your random position won't be so random though

royal linden
ivory bobcat
#
Get a random value
Get another random value
Create a vector with all three values being equal to the first random value```
summer stump
ivory bobcat
#

I'm assuming you wanted to use rand like a short cut variable for randomly generating values.

royal linden
eternal needle
light moss
light moss
#

thank you very much

eternal needle
royal linden
#

yea

#

have to learn somehow

royal linden
ivory bobcat
#

Follow a tutorial

eternal needle
#

you really dont even need to do that yourself, unity already does frustum culling. You just need to not load things that arent nearby (like minecraft)

#

you will want to scale this down by a lot though, infinitely scaling worlds will have problems very quickly.

west obsidian
#

is there a Material.SetTextureOffset for rotating a material? I cant find anything on the material methods page for rotating a material around a point

#

(does this even belong in beginner? I still feel like a noob but Im not sure when I should start posting in #archived-code-general...)

royal linden
#

i keep getting this

#

its cloning once

eternal needle
west obsidian
west obsidian
#

I mean if its really hard to do I dont mind just using a mesh but I would rather do this with materials

swift crag
eternal needle
royal linden
#

thx

#

anyone know why the pos is not working

summer stump
summer stump
royal linden
#

inside the[]?

summer stump
#

So they all go to the same position

summer stump
rich adder
#

also 0,3 will only give 0 or 1 or 2

#

cause its ints

royal linden
#

oh yea thats right doesnt go from 1

west obsidian
#

like a scrolling material

#

I want to do the same thing for rotation

eternal needle
west obsidian
#

yeah

#

Im not talking about that

#

thats already done

#

Im talking about aesthetic animation

deft yacht
#

Hey guys sorry, I have one final error! : Assets\Plugins\Assembly-CSharp-firstpass\DG\Tweening\Plugins\Options\NoOptions.cs(11,2): error CS1513: } expected

But I have the closed Bracket so i can't work out what it wants me to do šŸ¤”

using System.Runtime.InteropServices;

namespace DG.Tweening.Plugins.Options
{
[StructLayout(LayoutKind.Sequential, Size = 1)]
public struct NoOptions : IPlugOptions
{
public void Reset()
{
}
}

#

any ideas?

summer stump
#

@deft yacht You are missing the ending brace } for the namespace (the one to match the red one)

#

Always count the braces. You have 3 opening ones and only 2 closing ones

rich adder
eternal falconBOT
#
Visual Studio Code guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

https://on.unity.com/vscode

deft yacht
#

how is this?

rich adder
#

you mind as well code on notepad if you're not configuring your ide lol

deft yacht
#

thanks, I'm new so still learning the program

#

thansk for the help!

summer stump
deft yacht
#

Okay I'll check it out, i just installed c# ddev kit exstention also

#

ah and now the unity one, did not know that exists ahaha

swift crag
#

Follow the instructions closely.

summer stump
royal linden
#

it still goes to one position

summer stump
summer stump
#

Start only runs ONE time, and you use that ONE rand value for the whole for loop

#

So of course they all spawn in the same place

#

You have to set rand and pos INSIDE the for loop

royal linden
#

but i made more

summer stump
royal linden
#

how do i put them into for loop

rich adder
rich adder
#

its ugly as hel

polar acorn
summer stump
royal linden
summer stump
#

So that means it would make a NEW position for each new object

royal linden
#

do i leave the var outside

shell ice
#

How would I be able to make it when a player spawns in they spawn in with a character already for multiplayer for vr?

summer stump
# royal linden do i leave the var outside

You want to SET the variables inside the loop.
randX, randZ, and pos need to be in there

You can DECLARE them wherever though. If you want to use them elsewhere, put them as a class variable (where randX are in your last screenshot). Or as a local variable in start

public class worldGen...
  // class variable
  public int randX;

  public void Start()
  {
    //local variables
    int random;
    for (...)
    {
        // all equals signs that you want to be unique go here
        randX = Random.Range(0,10);

        random = (whatever);
        //use the values
    }
  }
royal linden
#

i dont understand why i have to define randX and randz inside the loop is it bc at the start it will choose a random value and stay like that?

summer stump
# royal linden i dont understand why i have to define randX and randz inside the loop is it bc ...

You don't define them in the loop. You assign them. I added the type (int) where I declare a variable.
And the = where I assign. If I put int at both places, it would create a new local variable, disconnected from the class variable one.

So game starts (simplifying it):
It reads the "definitions", one time

Then it gets the message to Start()

It reads the variables inside one time. (If rand was 2, it would have been (2,0,2)).

Then you looped over objects and spawned all of them at that position.

If it's INSIDE the foor loop, it would assign a new value to the variable each iteration.

royal linden
swift crag
#

the for loop will run the statement below it num times

#

since a block statement is below it, everything in it will run num times

#

anything that isn't inside that for loop will run once

rich adder
royal linden
#

thankyou i understand for loops 100X better

#

@summer stump

deft yacht
#

I know this isn't a coding problem but a unity issue, I apologise wasnt sure which channel to go to, but this is my final error 🄲

fiery notch
#

hello! I am currently making a breakout game and had a question, I have everything completed except for one thing. I want to make it to where if the ball hits a certain block, it goes a certain speed, such as if it hits a red block, it would be fast.

rich adder
#

if(hit.comparetag("RedBrick")
movespeed = moveSpeedRed

#

^ example, don't copy

royal linden
#

anyone know a good method to make sure that the assets are on the ground

queen adder
#

Need help

        public void SelectCharacter(CharacterData data)
        {
            // Close the character selection panel
            mainMenu.characterSelectionPanel.SetActive(false);

            // ...then set the "character using" in the DataCarrier
            for (int i = 0; i < characters.Length; i++)
            {
                if (data == characters[i])
                {
                    DataCarrier.chosenCharacter = i;
                    PlayerPrefs.SetInt("SelectedCharacterIndex", i);
                }
            }

            PlayerPrefs.Save();

            mainMenu.characterIconPresenter.sprite = data.icon;
        }

When I save the selected char it saves it but it does not the icon so when I select one then go into game and come back to menu its still selected but it shows the icon of the default one and not the one thats saved

public void LoadValues()
{
        int selectedCharacterIndex = PlayerPrefs.GetInt("SelectedCharacterIndex", 0);
        DataCarrier.chosenCharacter = selectedCharacterIndex;

        CharacterData selectedCharacter = DataCarrier.characters[selectedCharacterIndex];
        mainMenu.characterIconPresenter.sprite = selectedCharacter.icon;
}

Im loading the prefs in another script

shell ice
#

Is someone able to help me out? Can't find out why my legs and feet wont move left and right, forward and back. On a test model it worked fine but I don't understand what's wrong.

teal viper
teal viper
#

Not really a coding question btw

shell ice
#

Where would I go for questions like these?

static cedar
shell ice
#

Ok

magic smelt
#

I have the following code, that is working perfectly, but is there a way I can do this mathematically without hard coding the coodinates?

float[] yPositions = { 0, -7.5f, 7.5f, -15, 0, 15, 7.5f, -7.5f, 0 };

for (int i = 0; i < xPositions.Length; i++)
{
    float x = xPositions[i];
    float y = yPositions[i];

    print($"X: {x}, Y: {y}");
}```
The result should be:
X: -30, Y: 0
X: -15, Y: -7.5
X: -15, Y: 7.5
X: 0, Y: -15
X: 0, Y: 0
X: 0, Y: 15
X: 15, Y: 7.5
X: 15, Y: -7.5
X: 30, Y: 0
teal viper
#

Are these number sequences follow some kind of linear pattern? If not, then you're probably better of with keyframes like you have now.

magic smelt
#

I would love to do something like minX = -30, maxX = 30, minY = -15, maxY = 15

teal viper
#

Well, then there's no way to do it mathematically(unless you want to train an ML ai to find some pattern in your coordinates).šŸ˜…

magic smelt
#

just cant figure out the math to do this correctly, i came close few times ;P

teal viper
#

Basically, it's hard to derive a mathematical function from your data.

magic smelt
# teal viper It would work if your sequences were changing linearly. But they have repeating ...

I did this earlier and it almost worked perfectly, it was just missing 2 gameobjects:
X: 0, Y: - 15
X: 30, Y: - 15

minX = -30,
maxY = 15f,
minY = -15f,
thresholdX = 15,
thresholdY = 15; // Adjusted thresholdY to match the expected output

for (float x = minX; x <= maxX; x += thresholdX)
{
    for (float y = minY; y <= maxY; y += thresholdY)
    {
        print($"X: {x}, Y: {y}");
        Vector2 spawnPosition = new Vector2(x, y);
        Instantiate(gridManagerPrefab, spawnPosition, Quaternion.identity, gridArea.transform);
    }
    // After each row, adjust the Y coordinate for the next row
    minY = minY == -7.5f ? 0 : -7.5f;
}```
hushed spire
#

Will calling an Invoke inside my method to start the method again every x seconds lead to any issues down the line?

rich adder
#

better using coroutine

hushed spire
#

Just using startcoroutine inside the coroutine?

rich adder
#

just a while loop would suffice

hushed spire
#

But I need it to only run once every minute or so

#

Won't using a while loop and making a manual timer impede on runtime as it's checking that every frame?

rich adder
#

its a Coroutine which kinda works async

#
IEnumerator Repeat(float timeBetween = 60)
{
    while (true)
    {
        yield return new WaitForSecondsRealtime(timeBetween);
        //do the thing

    }
}```
hushed spire
#

Ah ok

#

That does make sense

teal viper
hushed spire
#

while(true) feels cursed to use in a practical sense though lmao

#

Appreciate the help

rich adder
#

MyCoroutine = null;

MyCoroutine = StartCoroutine(Repeat())

StopCoroutine(MyRoutine)

hushed spire
#

I usually just do StartCoroutine("nameOfCoroutine")

#

Is that bad code or just down to prefrence?

rich adder
#

using strings is not type safe

hushed spire
#

Meaning?

rich adder
#

if you mispell it the editor has no idea

hushed spire
#

But if I just copy paste the name there's no mispellings to be had

#

Though editing later on it's possible to accidentally edit it

#

So I do see where you're coming from now

rich adder
#

yus

hushed spire
#

Thank you again!

deft yacht
static cedar
teal viper
deft yacht
static cedar
# hushed spire Is that bad code or just down to prefrence?

It kind of is a bad code. UnityChanThink
Even if u just copy paste it or smth, just changing the name of the method will still break it. You have the nameof() to get changed along with it (using with ctrl + r + r in visual studio not code to rename something and update all references to that thing).
But i'd rather avoid relying on string inputs for stuff like this anyways.

#

Here's an extra reason why not to use string input ig.

/*Declaration*/
public Coroutine StartCoroutine(string methodName, object value = null); 

/*Description*/
//Starts a coroutine named methodName.

In most cases you want to use the "StartCoroutine" variation above. However "StartCoroutine" using a string method name lets you use "StopCoroutine" with a specific method name. The downside is that the string version has a higher runtime overhead to start the coroutine and you can pass only one parameter.
hybrid karma
#
IEnumerator Mark(int i)
    {
        HighlightColumn(i, Color.blue, 0, array[i]);
        yield return new WaitForSeconds(delay);
    }
``` when i call this there is no delay, the variable is define and it works elsewhere in the script, idk what to do
slender nymph
#

you're not delaying anything there. you're calling the HighlightColumn method, then it waits. but since nothing comes after the wait nothing is being delayed

hybrid karma
#

if i put the delay before it still doesnt delay

slender nymph
#

then either delay is zero, or by "doesn't delay" you actually mean that it only delays for the first time you call it, then every time after that you don't see any delay happening. and if the latter is the case then you're probably just starting the coroutine in update without doing any sort of checks for whether it is currently running or not

#

also keep in mind that coroutines do not delay the calling code in any way (with the exception being starting a coroutine inside of another coroutine and yielding that)

hybrid karma
#

oh, i need to delay the calling code, but i dont want the calling code to be a coroutine

slender nymph
#

is that code inside of update?

hybrid karma
#

no

slender nymph
#

then it needs to be a coroutine

#

or you need to be calling the method over and over and use if statement(s) to control what part of that code executes

hybrid karma
#

ok if the calling code is a coroutine then can i keep the delay in Mark? how do i make the delay in Mark work

slender nymph
#

yield return StartCoroutine()