#archived-code-general

1 messages Β· Page 103 of 1

heady iris
#

if you dragged the wrong slider into the "time slider" field

#

then you would have the volume slider changing both volume and time

heady iris
#

prove it by clicking on the time slider field and making sure it takes you to the right place

gray mural
heady iris
#

no, i can imagine exactly what the problem is

#

show your whole script, though.

gray mural
#

!code

tawny elkBOT
#
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.

heady iris
gray mural
gray mural
gray mural
#

because it does not work properly

heady iris
#

what if you get rid of the onValueChanged listener from the volume slider entirely?

#

does it still somehow change the time?

gray mural
heady iris
#

you guess?

gray mural
#

actually that was changed just when moving the slider

heady iris
#

i do not understand what you have or have not done

#

did you remove the event listener?

true palm
#

hey so Im getting a object not set to an instance of an object error and the wierd part is that its checking for gameobjects with a tag and giving me an error even though there is a game object with the tag. If anyone can help that would be great

heady iris
#

and did that change the behavior?

gray mural
#

but no, wait, I have just played and it was also changed a bit too

gray mural
true palm
heady iris
#

i forget if tags can have whitespace at the ends

true palm
heady iris
#

well, since it didn't find an object, the tag was not the same

#

does this object exist in the scene?

#

it's not going to find a prefab

leaden ice
true palm
#

the object is a child in a prefab. The player is checking for the tag and the prefab is instantiated on the player

leaden ice
#

Or the tag is wrong

#

without further details we can't say more than that

true palm
#

the tag is right because in the code i added a space to the end to see fi that was the name and then it gave me an error saying that that asnt a tag. so It should be working

leaden ice
#

Also it doesn't really sound like FindWithTag is an ideal way to handle this - why not just grab the reference when you instantiate the prefab.

leaden ice
#

Instantiate returns a reference to the newly created object

#

would be really silly if it didn't

true palm
#

I need to set a variable to an empty game object that is on the muzzle of the gun. So that muzzle flash can apear. how would I do that in the way you are saying @leaden ice

leaden ice
heady iris
#

put all of the references you need on a component that's on the root of the prefab

#

now you can grab them

leaden ice
#

yes - it's poor practice to try to reach inside other objects

heady iris
#

because those objects can get rearranged later

#

and now your code doesn't work

true palm
#

ok thats pretty smart @heady iris

heady iris
#

it adds a lot of complexity

#

generally speaking, you should avoid "finding" stuff

#

it leads to extreme agony:

#

finding a component in your parent is less prone to breakage, since there are fewer places to look

#

i do that for my UI system

#

all of the various bits and bobs find a UI Manager in their parent and register themselves with it

rugged storm
#

yo making a meteos clone and when i calling the meteos "packets" when i launch packets i want to make them into a "Packet group"

public class PacketColumn
{
    public List<Packet> packets;
    public int height;
    public int xpos;
    public PacketColumn(List<Packet> packets, int xpos)
    {
        this.packets = packets;
        height = packets.Count;
        this.xpos = xpos;
    }
}
public class PacketGroup
{
    public List<PacketColumn> columns;
    public int lenth;
    public PacketGroup(List<PacketColumn> columns )
    {
        foreach ( var column in columns )
        {
            foreach (var ccolum in columns.Where(c => c.xpos == column.xpos))
            {

            }
        }
        this.columns = columns;
        lenth = columns.Count;
    }


}```
however i will sometimes pass redundant columns (ones with the same x pos) into this group how would I go about combining them into 1 column in when defining a packet. i think I'm on the right track with the foreachloops but im not sure.
simple egret
#

Combining them, as adding up their heights? Then yeah you're on the right track, you need to do ccolum.height += column.height in the inner for loop.

#

And remove all duplicate columns after that. I'd just use a second List for that

true palm
#

@leaden ice i am now getting the same error but on this new line: muzzle = GetComponent<GunComponents>().muzzle;
But GunComponents.muzzle is defined on all guns

heady iris
#

GetComponent will look on the object that your component is attached to

#

if it's on a different object, then it won't work

gray mural
#

onValueChanged

true palm
heady iris
#

then it won't work

#

the player does not have a GunComponents component

#

call it on the gun game object

true palm
# heady iris call it on the gun game object

it is telling me i need an object reference to set the variables. You said that I cant do getComponent on something that doesnt have the component so how should I set the reference?

heady iris
#

gunObject.GetComponent<GunComponents>(), for example

#

where gunObject is a game object that has that component on it

true palm
#

ok

rugged storm
true palm
heady iris
#

i didn't say to do that

#

i said to call GetComponent on the gun object

#

you need a reference to the gun object so that you can get the component from it..

true palm
#

ok

leaden ice
#

wdym "the same error"?

heady iris
#

you're getting the Player component, then trying to get the Weapon component from the same game object

glossy basin
#

Hello there, whats the name of the 2D channel on this discord?

#

2D tools?

heady iris
heady iris
#

2D tools would be relevant for 2D art, yes

glossy basin
#

Thanks!

heady iris
#

otherwise, you probably just need to ask in the relevant channel for your specific problem

simple egret
granite nimbus
#

is it ok practice to keep an array and a hashmap of exactly the same data, syncing them on change, and use for different purposes?
it feels very natural and very stupid at the same time

leaden ice
heady iris
#

well, a list and a dictionary

#

but it's not a crazy idea

thick socket
#
using UnityEngine;
using UnityEngine.UIElements;

/*
* This file was auto-generated by the UIToolkitAutoReferencesPostprocessor class
*/

namespace " + FolderName + @"
{
    public class " + FileNameVariable + @" : MonoBehaviour
    {
        private VisualElement root;

" + PrivateElementReferencesVariable + @"

" + PublicElementReferencesVariable + @"

        void GetVEElements()
        {
            root = GetComponent<UIDocument>().rootVisualElement;
        }
    }
}";

        private const string PrivateElementReferenceTemplate = @"        private " + ElementTypeVariable + @"" + PrivateElementNameVariable + @";";

        private const string PublicElementReferenceTemplate =
            @"" + PrivateElementNameVariable + @" =root.Q<" + ElementTypeVariable + @">(""" + ElementIDVariable + @""");";

        #endregion
    }
#

what do the @ signs do here?

leaden ice
thick socket
#

thx

heady iris
#

that's a very interesting looking file

leaden ice
#

It looks like a template file for a code generator

thick socket
#

^^

#

grabs names and things from UI toolkit docs

heady iris
#

ooh, I see

thick socket
#

so I don't have to try and type everything exactly perfectly

heady iris
#

i kind of see

thick socket
#

however I didn't make it...trying to modify it to work exactly as I want πŸ˜„

heady iris
#

namespace " + FolderName + @"

#

i can't parse this

thick socket
#

FolderName is a variable above

simple egret
heady iris
#

ah!

#

yes, that would do it

#

code generation: not even once, man

#

i was doing research work involving a C source generator and a source-to-source obfuscator

#

infinite misery all the time

granite nimbus
# leaden ice it's ok - sure. But it might not be necessary. What's the use case?

like I want to do

for (int i = 0; // etc...)
  for (int j = 0; // etc...)
    // operate on array

and at the same time I want to have a mapping (particularly int2 to MyClass)
ofc I can just pack it into a struct like this:

public struct MyStruct
{
  public int2 coords;
  public MyClass myClassInstance;
}

and iterate with for loops on a struct, and still have mapping
but it feels like an unnecessary level of complexity, I'd like to go with array+hashmap way
I wanted to ask if this is a very stupid practice or it's ok to do that πŸ˜„

granite nimbus
leaden ice
#

I would just do:

Dictionary<Vector2Int, MyClass>```
#

no need for the array

granite nimbus
leaden ice
#

unless you need to - but in that case you can still use a nested for loop if you want

granite nimbus
rugged storm
# simple egret That's the question I'm asking. What do you mean by "merge"

By merge I mean like when I run clear check logic on the bottom 3 blocks, it will launch them, that will make a column of each of the bottom 3 blocks and the blocks above it and pass thoes columns into a new packet group, i want to know how to take thoes 3 redundant groups and combine them into one that is just the bottommost block up

simple egret
#

Whoa
I'm having issues parsing that sentence

wet gyro
#

hello guys, i'm facing some problem here using Analytics and Dashboard. the standard events are working as gameStart, gameEnded, newPlayer and many others. But the custom event isn't working, even though I have configured and enabled it on the Dashboard.

rugged storm
# simple egret Whoa I'm having issues parsing that sentence

all thats really import I guess is, it will make 3 columns (lists of blocks) each containing one of the 3 "launched"(bottom 3) blocks and all blocks above it(which for all but the 3rd from the bottom will include one or more of the other launched blocks) , how do I combine those 3 columns? into one without the overlap making multiple references to the same block?

simple egret
#

So those 5 blocks are in a list and you want to put them into one "group", by their column index

#

I'd use a 2D collection, like a List<List<BlockGroup>> and dynamically add blocks to it as they come through

true palm
#

Hey so the muzzle flash system in the shoot function is not working and I do not know why. Can anyone help? Heres the script: https://hatebin.com/pihwyylqqh

dusk apex
#

Any and all info is necessary.

true palm
#

all the shooting works but the muzzle flash prefab is not being instantiated

dusk apex
#

Where do you instantiate the muzzle flash?

#

I'm guessing line 400

true palm
#

in the shoot function on line 340

solemn rune
#

Question.. I rotate / swing a gameobject with a mouse input. I get the axis of the mouse in Update, clamp the axis between 0 and a max speed, and then apply that clamped axis as a euler to rotate the object. Everything looks and feels smooth (project runs at 300fps). Now, I need to make the input frame rate independent, so I multiply the axis with Time.deltaTime (and multiply the outcome because it's obviously a lot slower). I get the same speed of the movement, but it looks and feels way choppier then when I didnt use Time.deltaTime

rugged storm
#

no... okay when i "match", the bottom 3 blocks each block find all the blocks above it, and makes them into a list including it's self called a column, like this image, each color representing a column, how do i combine the columns into 1

solemn rune
#

I must be using it wrong somehow

leaden ice
simple egret
solemn rune
#

I'm using Input.GetAxis("Mouse Y") per update though

leaden ice
true palm
leaden ice
#

no need for deltaTime

leaden ice
#

"didn't work" is very vague

#

if the code is running and you're not getting errors - then the Instantiate is happening

leaden ice
solemn rune
#

Ahhh yeah i see now.. Thanks, that was dumb of me!

true palm
#

It isnt showing up in the right position then

leaden ice
#

it might be spawning somewhere you don't expect, or it might be getting destroyed right after

#

first place to check is the hierarchy window

true palm
#

ok

rugged storm
true palm
dusk apex
#

So it's working.

#

Modify the position and rotation to fit your needs.

#

Likely the data that you're wanting to use aren't good

true palm
leaden ice
#

It's also kinda weird you're maintaining your own Vector3 muzzlePos variable in this script - just read the position directly from the muzzle when you need it

#

muzzle = loadout[currentIndex].prefab.GetComponent<GunComponents>().GunMuzzle;
You're pretty explicitly reading it from the prefab right now πŸ‘οΈ

true palm
#

yeah and thats my issue

#

Im just having trouble getting the instance of the instantiated gun

leaden ice
dusk apex
#
var instance = Instantiate(gunPrefab, ...);```
true palm
leaden ice
#

it is the return value of the Instantiate function

solemn rune
#

Another question relating to Input and frame rate indepenency. So, I was making the mistake in regards to Input.mouse axis etc. But, what I am doing wrong is: I am clamping the axis in Update, which is causing problems

#

I'm using the axis to calculate a euler rotation. what would be a good way of clamping this and making it frame rate independent?

leaden ice
solemn rune
#

you mean clamp the actual rotation, rather then the amount of eulers to add? But, if I do that in update, wouldnt that then Also go faster the more updates per second?

#

to clarify: I use the axis to calculate how many eulers to add or subtract from a certain rotation

leaden ice
#

It will move as fast as you move your mouse

#

it's not going to give you input values if the mouse isn't moving

solemn rune
#

Yeah i dont want that functionality (im not moving the camera but a game object)

leaden ice
#

I don't understand what you're asking

#

clamping the "amount of eulers to add" isn't helpful

#

you want to clamp the max up/down looking angle right?

solemn rune
#

sorry, i'll post code

#

!code

tawny elkBOT
#
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.

solemn rune
#
void SwingForwards(float axis)
{
        axis = 2f * axis;

        axis = Mathf.Clamp(axis, 0, ballSwingMaxSpeed*Time.deltaTime);

        anchorRotationEulers -= new Vector3(anchorRotationSpeed * forwardSwingSliderSpeed * axis, 0, 0);

        ballAnchorRot.transform.localRotation = Quaternion.Euler(anchorRotationEulers);
           ballAnchorPos.transform.position += ballAnchorPos.transform.forward * ballSwingMovementSpeed * forwardSwingSliderSpeed * axis;
} ```
#

calling this function per update

leaden ice
#

you're only clamping the amount to rotate by - not the actual rotation here.

solemn rune
#

the Time.deltaTime i've just added

leaden ice
#

What are you trying to do

solemn rune
#

I'm trying to give the rotation a max speed

somber nacelle
solemn rune
#

indepently from the frame rate. So there is a max speed with which you can move the object. But slower movement is ok.

solemn rune
leaden ice
#

There's so many different multipliers you have here - seems confusing
forwardSwingSliderSpeed
2 < a magic number
anchorRotationSpeed

solemn rune
#

yeah, it Is confusing, totally agree ha. What I'm doing is: moving a gameObejct, and then rotating a gameObject within that (kinda like a wrecking ball on a crane going forwards and backwards)

#

and tbh, I have no idea why I multiplied forwardSwingSliderSpeed with the position And the rotation... It's been a while since I wrote that

#

The 2 is basically the "Main" speed (should have been a variable). Then there is the max swing speed and max movementspeed. I was rewriting everything, so I think I'll take out the SliderSpeed ha

vestal summit
#

can someone explain what does this mean?
public class Name => name;

leaden ice
#

unless you mean class as a placeholder

vestal summit
leaden ice
#

for a type

harsh bobcat
#

its like a mini function

vestal summit
#

imagine the class is an actually class with a name

leaden ice
true palm
#

@leaden ice I got the output from the instantiate and got the muzzle reference from it but the muzzle flash still instantiates at a different location

leaden ice
heady iris
leaden ice
#

do more debugging

heady iris
#

since that changes the meaning

#

the ol' reliable is Foo

#

or maybe just MyClass or SomeClass

vestal summit
#

basically this

rugged storm
#

@simple egret I figured out I think I should use List<>.union for it but I'm not sure how to pass a list of lists into Union

leaden ice
#

as in my above example

harsh bobcat
#

basic lambda expressions:

    public float Square(float a)
    {
        return a * a;
    }
    public Func<float, float> Square = (a) => a * a;

either way you can do float num = Square(2);

solemn rune
#

But, axis = Mathf.Clamp(axis, 0, ballSwingMaxSpeed*Time.deltaTime ) still doesnt seem to give me the desired behaviour unfortunately. The higher the FPS the faster the movement..

vestal summit
leaden ice
#

It defines a property that outside classes can call to read that data

thick socket
#
            sortedList = itemsList.OrderByDescending(o => o.item.rarity).ThenByDescending(o => o.item.level).ThenBy(o => o.item.itemType).ThenBy(o => o.item.name).ToList();

soo

harsh bobcat
#

or use brackets every time

thick socket
#

this should have all legendary items at the top...then it should sort and so the highest level legendary item is at the top right?

#

why does an epic item(leveled above everything else) take precidence here and go to the very top of the sort?

vestal summit
heady iris
#

i presume your rarities are represented as an enum

vestal summit
#

read-only

thick socket
heady iris
thick socket
vestal summit
#

similar to { get ; private set }

leaden ice
# thick socket

you sure that level 6 thing has the right rarity? Maybe it's colored wrong

leaden ice
#

if you want mythic first?

thick socket
leaden ice
#

oh nvm you have that

vestal summit
#

then this thing => pretty much means return

heady iris
thick socket
#

everything sorts correctly until I level up items

heady iris
#

which implicitly returns the expression, yeah

harsh bobcat
thick socket
#

nevermind Im stupid

#

was sorted by slot and not rarity....

#
            sortedList = itemsList.OrderBy(o => o.item.itemType).ThenByDescending(o => o.item.level).ThenByDescending(o => o.item.rarity).ThenBy(o => o.item.name).ToList();
#

that was the actual code

heady iris
#

splat

harsh bobcat
#

quick check, if I have GameObject GO = null will GO.transform be null or throw an error?

heady iris
#

it will throw an exception.

harsh bobcat
#

thx

heady iris
#

dereferencing a null ref will throw an exception

leaden ice
harsh bobcat
#

ah thought so

#

thanks

wide terrace
#

But you can use a null conditional operator if you don't want to manually check if GO is null first

GO?.transform

If GO is null, the following property accessor won't be evaluated, and the result of the entire expression will be null

leaden ice
#

in general yes

#

but in Unity - with UnityEngine.Objects, no

wide terrace
#

how bad did I do? πŸ˜…

#

ah shucks

leaden ice
#

this won't work properly with Unity's overridden == operator

#

i.e. if the object is destroyed, it will still try to access the transform

#

and you'll get a MissingReferenceException

wide terrace
#

That is really good to know

leaden ice
#

so in general - try to avoid the ? family of operators with UnityEngine.Object references

lucid valley
wide terrace
#

I know just enough to confidently say something stupid and hope you all catch my mistakes πŸ‘€

wide terrace
wide terrace
sinful galleon
#

Can someone write me code for an entire open world game pls@I will pay $5

somber nacelle
#

lol $5 won't buy you a single line of code

#

also !collab

tawny elkBOT
sinful galleon
#

Ok

#

$4

somber nacelle
#

can you take your trolling bullshit elsewhere. it's not appreciated here and there's no off topic allowed here

sinful galleon
#

Why r u so angry lmao

somber nacelle
lean sail
#

who said hes angry, off topic stuff just isnt allowed

sinful galleon
#

It’s called tone

#

Anyways bye bye

wintry stone
#

using the new unity input system is it possible when disabling the gameobject to not disconnect the controller from it?

lean sail
#

is there any standard approach to how movement/leg collisions with active ragdolls should be done? Just curious if there is another method that i havent tried
I have a character setup with configurable joints, and a script for each body part to copy a walking animation. This works fine when the character is in the air but im running into issues where the legs just wont stop colliding with the floor which stops the hip movement [see image 1]
I tried setting the feet to be frictionless, but this doesnt fix the issue on upward slope. Also the player slides around, which is annoying to deal with.
I tried adding a constant force component to the hips and it works nice on the ground. On slopes however i can see the feet moving but they keep colliding and sometimes just drag on the floor
also tried animation rigging but it doesnt seem to be what i want because it kinda takes away from the active ragdoll movement (and im horrible with using it on a moving ragdoll)

thick socket
#
IEnumerator TapToClose()
    {
        yield return new WaitForSeconds(1.5f);
        var tapToClose = root.Q<VisualElement>("TapToClose");
        tapToClose.style.display = DisplayStyle.Flex;
    }

StopCoroutine(TapToClose());

#

this is how I would stop the coroutine so it doesn't execute if its been waiting for...say 1s out of the 1.5s

#

(cause it isn't working)

wide terrace
dull yarrow
#

Funny thing that is happening on my code
I am calling a function that clears my inventory and then another function that adds a item to the first open slot.
If i call the function one time, it clears and then it adds the item to first slot. But if i call the function again, it clears the inventory but it then adds the item to the second slot instead of the first
I dont know why this is happening

        for (int i = 0; i < inventorySlots.Length; i++){
            InventorySlot slot = inventorySlots[i];
            if(slot.transform.childCount == 1){
                Destroy(slot.transform.GetChild(0).gameObject);
            }
        }
    }```
``` public void AddItem(Item item ){
         for (int i = 0; i < inventorySlots.Length; i++){
            InventorySlot slot = inventorySlots[i];
            if(slot.transform.childCount == 0){
                SpawnItemn(item,slot);
                return;
            }
        }
    }```
heady iris
#

so you do clear, add, clear, add?

dull yarrow
#

On the second add, the item spawns on the second slot

heady iris
#

what if you do it again?

#

does it go in the third slot?

dull yarrow
#

No, goes to the first

#

I placed a log on the add item

#

and its doing 2 times when the time he places it on the second slot

#

Its really strange

heady iris
#

oh!

#

it's because the object isn't destroyed until the end of the frame

#

unparent the objects' transforms before you destroy them

#

i've had this problem many times

#

e.g. while (transform.childCount > 0) { Destroy(transform.GetChild(0).gameObject)); }

#

this spins forever

dull yarrow
visual fractal
#

Does anyone know what the error 'Assets\Character Controller\Scripts\Components\PlayerStats.cs(6,13): error CS1012: Too many characters in character literal' means? The code its talking about is [Header('Stats')]

heady iris
#

you are using single quotes

#

those are for character literals

visual fractal
#

Ah.

#

Ok.

heady iris
#

i.e. a literal that represents only one character

visual fractal
#

Thanks.

woeful slate
#

are scriptable objects mainly meant to be interacted with through the editor?

#

in terms of defining their values

cyan cave
#

Is there a reason why private void OnCollisionEnter(Collision collision) { if (collision.gameObject.Tag == "Player") { tankHealth.TakeDamage(damage); } }
Keeps getting me a Namespace name can't be found CS0246 error when I try calling the health script over

swift falcon
#

I just thought about this, but why shouldnt camera input be frame independent

#

Isnt it better if sensitivity is the same for everyone

cosmic rain
swift falcon
cyan cave
# cosmic rain Share the whole error.

Assets\Scripts\EnemyDamage.cs(7,12): error CS0246: The type or namespace name 'TankHealth' could not be found (are you missing a using directive or an assembly reference?)

cosmic rain
swift falcon
#

Like first person camera controller

cosmic rain
cyan cave
#

and for that line I have
public TankHealth tankHealth;

cosmic rain
cyan cave
#

Yes in the script I'm trying to call as a public class

cosmic rain
cosmic rain
swift falcon
cosmic rain
#

You usually need to multiply a constant value by delta time, because you want the portion of that value based on the time between frames.

#

Mouse input is already a portion of the movement that the mouse moved between the frames.

cyan cave
foggy monolith
#

can someone help me my games not downloading the packages i need

cosmic rain
cyan cave
cosmic rain
#

line 24 should be tankHealth.TakeDamage(damage); though

cyan cave
#

@cosmic rain After everything it's now saying this it seems like
Assets\Scripts\EnemyDamage.cs(24,24): error CS0122: 'TankHealth.TakeDamage(float)' is inaccessible due to its protection level

cosmic rain
#

Because TakeDamage is private. You should be able to solve that if you post in this channel.

cyan cave
#

I appreciate the help, thanks! @cosmic rain

lapis ravine
#

just started unity

#

what should i learn

somber nacelle
#

do the pathways on the learn site, they go through everything you need to get started

lapis ravine
#

alright

#

which one do i click

#

ohh

somber nacelle
#

start with unity essentials

lapis ravine
#

nvm

#

the first one

#

ye

tender fog
#

how do I make it so that an object doesnt rotate around the origin
i want it to rotate around the center of itself
if that makes sense
heres the code im using

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MouseLook : MonoBehaviour
{

    public float mouseSensitivity = 100f;
    public Transform playerBody;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;


        playerBody.Rotate(Vector3.up * mouseX);
    }
}
lean sail
#

what do u define as the center of itself, if not the origin?

somber nacelle
#

also don't multiply mouse input by delta time, mouse input is already frame rate independent and anyone teaching otherwise is wrong. when you remove that make sure to lower your mouse sensitivity variable both in the script and the inspector

tender fog
#

basically just an FPS

somber nacelle
lean sail
#

you would turn your head by moving your head around the origin..

somber nacelle
lean sail
#

can u show a screenshot, something is likely not setup correctly

tender fog
somber nacelle
#

yeah not centered

tender fog
somber nacelle
#

the child object should be at 0 on both the x and z axes so that when you rotate around Y it rotates in place

lean sail
#

im very confused by this image, how is that box at -15x and 2.11z but the camera is right beside it at 17x. Also what is parented on what

tender fog
#

The empty player object was somewhere else but I thought it was aligned with everything else

#

(I thought it had the collider on it but it did not)

#

so it was rotating around that

#

not the origin

tender fog
tender fog
#

So, now that my script is working, how do I add vertical rotation to this camera script? I tried a bunch of things but everything either behaved in an unpleasant way or flipped the rotations or messed up the Z and I have no clue what was happening.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MouseLook : MonoBehaviour
{

    public float mouseSensitivity = 3f;
    public Transform playerBody;
    Vector3 amongus = new Vector3(1,0,0);
    // Start is called before the first frame update
    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    // Update is called once per frame
    void Update()
    {
        float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity;


        playerBody.Rotate(Vector3.up * mouseX * mouseSensitivity);
    }
}

lean sail
#

have you tried cinemachine? seems like you're trying to code something that exists

void basalt
#

It's going to look something like this

#

avoid rotating quaternions for something like this

#

It's going to look very similar for vertical camera movement. I probably have the axes wrong as well.

tender fog
#

Just added the Y and it works now just inverted

#

i guess the eulerAngles thing did the trick thanks

void basalt
#

make the value negative

#

to un-invert it

tender fog
#

I got it now

#

thanks very much

void basalt
#

@tender fogYour mouseX and mouseY variables will also need to be global

#

not local

#

since the values need to be saved between frames

void basalt
#

at the top of the class

#

float mouseX;
float mouseY;

tender fog
#

yeah I did that

void basalt
#

great

tender fog
#

it gave an error since I refferred to mouseX in the definition of mouseX

tender fog
tame iris
#

I am using Native Gallery to get audio and play it. Can anyone tell me why is it too loud? like even If I put audio volume to 0.0001 it still is too loud. https://gdl.space/imugasocoq.cs

lean sail
#

did u uncomment the parts about volume by chance, because its commented out in that script

tame iris
#

I think the audio is too low quality. how do I fix this?

void basalt
tame iris
void basalt
#

go to the audio file in unity

tame iris
void basalt
#

and see if there's a compression setting

#

oh I see

lean sail
#

are you playing it with a custom script?

void basalt
#

This is some pretty advanced stuff

#

It's likely a low sample rate or something

#

since you're designating that

tame iris
void basalt
#

log the sample rate

#

and probably number of channels

#

those are going to be the main factors in dictating quality, I believe.

#

If they're different from the original audio source, then that's your problem

nova moon
#

How would I get an object that is being clicked on by my cursor? I'm making an rts style game, and I have my camera and cursor working correctly as far as movement goes, but am having some problems with selecting an object. This is the code I have for converting the mouse position from screen space to world space, but I'm not 100% sure it's correct. I've tried using an OverlapSphere or a raycast, but couldn't get either working. I think raycast would be the way to go, just couldn't seem to get it setup correctly I guess.

prime sinew
# nova moon How would I get an object that is being clicked on by my cursor? I'm making an r...

Sign up for the Level 2 Game Dev Newsletter: http://eepurl.com/gGb8eP

This Unity tutorial will teach you how to select objects using raycasts.

#UnityTutorial #Raycast #GameDevelopment

πŸ“¦ Download the project at https://www.patreon.com/posts/25656838

This tutorial was created in part with Jason Storey (apieceoffruit). Learn more about Jason b...

β–Ά Play video
#

Disclaimer: I haven't actually watched this vid. I just know it exists

nova moon
#

Ah found it. I was using ViewportPointToRay instead of ScreenPointToRay. Using the right function fixed it!

spice orchid
#

Hello everyone, i need some help with.. uh.. i don’t even know how that problem is called
i need to connect all nodes (the doorways) on a grid with hallways in my map generation algorithm.
The result of generator should look something like that on a picture.
I don’t know what approach to use here (pathfinding? cellular automata? graph?) and i don’t even know how that problem is called so i cant find anything on internet

#

the corridors must be able to connect with each other to minimise overall length of network, not just connect two points in space

dusk apex
fervent furnace
#

Your illustration shows tendency to pathfinding

spice orchid
dusk apex
#

Usually you'd have a collection of rooms or areas and simply randomize the selection of which is to be placed rather than procedurally creating entire mazes/dungeons.

spice orchid
spice orchid
#

i think this is some kind of network optimisation problem?

dusk apex
#

Doesn't sound related to networking.

#

Sounds like you simply need to implement some sort of procedural generation of connecting rooms using rules and whatnot.

smoky pike
#

I have a game where the player should be at the bottom of the camera and followed by the camera. However, whenever I add an offset to the camera's position in update, the camera y position just continuously decreases. Code:
Vector3 targetPosition = new Vector3(player.transform.position.x, player.transform.position.y-(screenHeight/2), -1); transform.position = Vector3.SmoothDamp(transform.position,targetPostion,ref velocity, smoothTime);

dusk apex
#

It goes negative infinitely?

smoky pike
dusk apex
#

Unless the camera is the player, it should just be the players position minus some offset.

#

Are you reassigning the offset anywhere?

smoky pike
#

nope

lean sail
#

Are your references set up correctly? The only time I had a camera fly off to infinity was when it was trying to point at itself

dusk apex
#

Relative to variable references

smoky pike
smoky pike
dusk apex
#

If the player was the camera, what you're describing would happen.

smoky pike
#

no the player values are correctly used

#

and the script is attached to the camera

#

when i don't add the offset, the camera tracks the player at the center of the screen

dusk apex
#

You'll need to show us some logs, the hierarchy or the inspector

#

The code is perfectly fine otherwise

#

It's most definitely a setup issue

spice orchid
dusk apex
#

The rules I'm referring to are if halls are allowed to overlap with other halls, rooms or whatnot.

smoky pike
#

this is the output log of the camera position from the initial startup

dusk apex
#

So either your offset is growing negatively, your player position is decreasing in the y axis or something else is occurring.

#

Assuming you aren't using some sort of local velocity variable - it needs to persist per iteration.

#

Showing more code may be necessary at this point

smoky pike
#

the "height" variable is just a number

dusk apex
#

Log the offset

smoky pike
#

`
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using UnityEngine.SceneManagement;

public class Movement: MonoBehaviour

{
private Vector3 velocity;
private float width;
private float height;
private gameObject player;
void Awake()
{
width = (float)Screen.width / 2.0f;
height = (float)Screen.height / 2.0f;
}

void Start(){
    velocity = Vector3.up*Time.deltaTime*.25f;
}
void Update()
{

    Debug.Log("CAMERA POSITION:" + transform.position+"Offset"+height);
    Vector3 targetPosition = new Vector3(player.transform.position.x,player.transform.position.y-height,-1);
    transform.position = Vector3.SmoothDamp(transform.position,targetPosition, ref velocity, smoothTime);
}

}
`

dusk apex
#

How to post !code

tawny elkBOT
#
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.

dusk apex
#

The above should not compile

smoky pike
dusk apex
smoky pike
#

oh

dusk apex
#

Where do you define player? it's private and not accessible by the inspector.

fervent furnace
dusk apex
swift falcon
#
        RaycastHit hit;
        if(Physics.Raycast(cam.ScreenPointToRay(Input.mousePosition), out hit))
        {
            if (hit.transform.TryGetComponent(out CityPointObject city))
            {
                citySelected = true;
                cityNameText.text = city.cityData.cityName;
                cityDescText.text = city.cityData.cityDescription;
                cityPopulationText.text = cityPopulationText + city.cityData.cityPopulation.ToString();
            }
            else citySelected = false;
       }

Why cant it get the city object? everything seems right

dusk apex
#

You can set a predefined capacity if needs be, for less reallocation

smoky pike
swift falcon
dusk apex
leaden ice
smoky pike
#

i think the problem is that the offset height value is 1170.

swift falcon
swift falcon
leaden ice
#

Have you even determined which thing is null yet?

dusk apex
swift falcon
leaden ice
#

Don't assume anything

swift falcon
#

Ill debug more rn

smoky pike
#

and the y position of the camera ends up being-1171

#

im testing the game on mobile so the screen height values might be off

dusk apex
#

So if height is that fixed value, then is the player position changing? (doesn't matter if he doesn't look like he's moving with the camera in game)
Is the position changing? Should it be a local position?

swift falcon
#
                if(city != null || city.cityData != null)
                {
                    print("not null");
                }

This prints

smoky pike
dusk apex
#

so city name text was null

swift falcon
dusk apex
dusk apex
#

Any of them being individually true would print with or

#

None of them had better be null rather than "well.. if one isn't null, let's print!"

quartz folio
#

Could have multiple objects, etc.

smoky pike
quartz folio
#

Please just learn to use the debugger instead of wasting time with a bunch of logs

swift falcon
# dusk apex Use and not or
                if(city != null)
                {
                    print("not null 1");
                }
                if (city.cityData != null)
                {
                    print("not null 2");
                }
                if (city.cityData.cityName != null)
                {
                    print("not null 3");
                }

all prints

quartz folio
#

It never prints if it is null

#

so if there's multiple objects, one of them null, you get no info

#

Also, cityNameText was never checked

swift falcon
dusk apex
#

Basically the program had already determined that one of the three possible references are null. It's simply up to you to find which one.

swift falcon
#

Im too ashamed to even say what the issue was

dusk apex
#

We don't care about the city name btw. Only references who are calling members can throw

swift falcon
#

But Yeah I fixed it thanks

wide terrace
#

You forgot to assign it in the inspector 😁

thorn pumice
#

hey peeps! im looking for a better way to do this im doing:
So, I have a list of entities for my game stored in a list. These are bussines entities (most likely will end up in a DB after prototyping). These entities have an ID.

To make it easier to play with these in the code, the ID is of the type of an ENUM, so I always know what im getting (ie: enum has UNIT_A, UNIT_B, so when getting something by ID "1" i just get by enum.UNIT_A)

This is really comfortable to manage stuff in the code - but it has a problem; every time that i add something to that list, i have to add a new entry on the enum. And its getting really uncomfortable.

Is there any way to do this without the enum?
Or maybe a way to "Create the enum" automatically when I change stuff on that list/db?

frosty lark
#

I think if each entity will be of a unique type you will need to keep a variable for the Enum.

#

You could just have a list of strings instead but you will need to know how to identify them.

frosty lark
#

What are the business entities do they all different from each other

thorn pumice
#

i wanted to avoid the idea of doing a GetEntity(value) with a value that I can get wrong. Thats the beauty of the enum

hard estuary
thorn pumice
#

thanks a bunch!

hard estuary
thorn pumice
#

mmmh then how do you solve the "getting the name of that entity right" problem? just using the value as suggested above?

#

well maybe you can do that and just create methods for more important entities
liek "GetEntityTownHall" and insider its just "return GetEntity("town_hall_id")

hard estuary
# thorn pumice well maybe you can do that and just create methods for more important entities ...

Depending on the situation I would just stick to enums, or create a ScriptableObject/Prefab for each entity so I could use those as a reference everywhere. The second approach ensures that the code won't contain any enums, so all the restrictions have to be configured through the inspector, therefore all the game rules would be more modular and could be created by game designers. But in the end, enums seem to be much easier to use if only the programmer is responsible for the game logic.

gray mural
#

The PlayBackgroundMusic() method is called several times in Update(), because audioSource.clip cannot be set instantly. How do I avoid it?
Should I use some kind of Coroutines with WaitUntil or just bool? Do not know how though.

private void Update()
{
    if (audioSource.isPlaying)
    {
        if (!changingTime) timeSlider.rawValue = (int)audioSource.time;

        ChangeTimeInputText();
    }
    else
    {
        PlayBackgroundMusic(); // this method :[
        ChangeTimeSlider();
    }
}
thorn pumice
hard estuary
restive jetty
#

been trying to figure this out for hours

#

am getting sick of it

#

this is a school assignment due in a couple days

#

help is needed lmao

#

all i want is for the enemy to chase the player 😭

simple egret
#

You're pretty much trying to put a cube-shaped thing, into a triangle-shaped hole

restive jetty
#

?

#

so confused

simple egret
#

.rotation is a Quaternion, a type that represents a rotation on 3 axes. But you try to put a single number into it

#

You cannot do that

restive jetty
#

so what should i do

#

didnt realise there is a beginner channel sorry guys

simple egret
#

First, tell us what this code is supposed to do

#

The rotation part, at least

restive jetty
#

its supposed to make the enemy look towards the player

#

and then i wanted to make it follow the player

#

and attack it

simple egret
#

Okay, so select the enemy in the scene and look at the arrows that appear. Is the enemy's forward direction towards the blue arrow?

restive jetty
#

i believe so...

#

but their is a red arrow going another way

#

or to the right of it

simple egret
#

Yeah that's normal, as long as the blue arrow points "forwards" it's set up correctly

#

And that the green arrow points up also

restive jetty
#

yep

simple egret
#

So you construct a direction vector there on the first line, so you can use the handy Quaternion.LookRotation(direction) function, so Unity constructs a rotation Quaternion for you

restive jetty
#

how do i construct a direction vector

#

do i just put that code in?

simple egret
#

You have that

#

First line

#

direction variable

restive jetty
#

oh yea

#

this one?

simple egret
#

Yes the first line

#

You can remove the second one entirely, you won't be needing it anymore

restive jetty
#

done

simple egret
#

Then use Quaternion.LookRotation(direction), put the result of that immediately into rb.rotation

#

And that's pretty much it, 2 lines

restive jetty
#

that look right?

#

wait nah it says angle doesnt exist

simple egret
#

Where did rb.rotation go?

restive jetty
#

replaced it with what Quaternion.LookRotation(direction)

simple egret
#

When I say

Put the result of X into Y
I mean, Y = X, in code

hardy cedar
#

this

simple egret
#

Y = X assigns the value of X into Y

restive jetty
#

there is no x or y though so im very confused

simple egret
#

It's example names

restive jetty
#

like in the code at least

#

oh

simple egret
restive jetty
#

so how do i get a result out of Quaternion.LookRotation(direction)

#

like do i just put that in

simple egret
#

Try it

restive jetty
#

gave me an error code

simple egret
#

Aight

restive jetty
#

also gave me an error code

simple egret
#
Vector3 direction = player.position - transform.position;
rb.rotation = Quaternion.LookRotation(direction);

Do yourself a favor and !learn how to work with Unity scripting

tawny elkBOT
#

πŸ§‘β€πŸ« 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/

restive jetty
#

alright will do thank you for the help

opaque schooner
#

hello, I have a problem, when doing

button.transform.SetParent(buttonParent);

it does nothing, same for doing it when instantiating and/or doing

button.transform.parent = buttonParent;
simple egret
opaque schooner
#
Button button = Instantiate(buttonPrefab, buttonParent);

I'm doing this but it just instantiate's it on scene and not parent

simple egret
#

Then debug required, is buttonParent assigned to the value you're expecting

opaque schooner
#

yes

simple egret
#

Prove it

opaque schooner
#

and if it wasn't there, wouldn't it just throw null?

simple egret
#

In Instantiate maybe, but for the other versions no

opaque schooner
#

what else could be be causing this?

simple egret
#

Nothing, the code is correct

opaque schooner
#

something in prefab/hierarchy?

simple egret
#

Maybe it's not executing on the object you think it is? Use something like Debug.Log(buttonParent, gameObject) and once you get the log pause the game, and select that log, it'll highlight the object that sent it in the Hierarchy

opaque schooner
#

YES

#

thank you

#

I was accidentally executing the code on manager instead of the correct object

#

and wasn't actually passing the parent object

#

so wouldn't this be a bug? when a null parameter is passed for transform but no error is thrown?

simple egret
#

For the parent no, passing null unparents the object

opaque schooner
#

oh

#

thanks anyways

mental pumice
#

Library\PackageCache\com.unity.burst@1.8.2\Editor\BurstAotCompiler.cs(981,27): error CS0234: The type or namespace name 'AndroidExternalToolsSettings' does not exist in the namespace 'UnityEditor.Android' (are you missing an assembly reference?) any fix for this werid error?

#

no way it fixed its self by just waiting

reef ridge
#

Hello,
I hope this is the correct channel to post this question in. I have installed Unity as a flatpak on Manjaro, and I am trying to setup autocompletion with omnisharp in Neovim. The LSP setup part is pretty easy, but the problem is that using the generated C# scripts, I am having errors.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

On line 3, the program is not finding UnityEngine. What I have found after googling, is that I should have a Library/UnityAssemblies folder, which does not exist. I have tried the many ways to create it, for example by closing Unity, deleting the Library folder, then reopening Unity, but it still doesn't work.
The same error is happening in the 5th line, with MonoBehavior

#

Thanks in advance for any help

cursive ember
#

Hello, why it says there is an error even though there isnt any?

simple egret
#

You're not supposed to build a Unity project. Unity takes care of that for you.
Just make sure you saved, then go back to Unity and it'll pick up your changes and compile them for you

cursive ember
#

But I use this

gray mural
#

just Ctrl + S everything

cursive ember
#

Unity can run normally but when I want to attach VS for debugging it isnt possible

simple egret
#

Is debug mode enabled in Unity?

#

The little bug icon bottom-right of the Editor

cursive ember
cursive ember
gray mural
mental rover
cursive ember
mental rover
#

I'd try closing both Unity and VS, then open Unity and regenerate project files

cursive ember
#

I closed everything rn

ashen yoke
#

nuke .vs folder

reef ridge
cursive ember
#

It doesnt get triggered

narrow lily
#

hey
i'm trying to make a madness combat game but i can't quite figure out how to import the flash sprites

mental rover
reef ridge
#

Okay thanks.

gray mural
narrow lily
#

i am trying to import a flash sprite sheet

gray mural
narrow lily
#

how can i do that

gray mural
#

you mean import in unity?

cursive ember
ashen yoke
#

search asset store/ github for importers

#

or write your own

gray mural
ashen yoke
cursive ember
#

Yes i have

swift falcon
#

how can i detect if 2 ui / images collide with each other?

gray mural
ashen yoke
#

i dont know efficient way but the one i used is to extract their bounds and test for overlap

swift falcon
#

or box collider 2d

cursive ember
gray mural
swift falcon
#

ok i added them this is my code btw

void OnCollisionEnter2D(Collision2D collisionInfo) {
        if (collisionInfo.transform.tag == "Shrine") {
            Debug.Log("succesfully found shrine");
        }
    }

why is this not working?

#

i have this code in my cursor image

swift falcon
gray mural
gray mural
swift falcon
#

pinned? wym

gray mural
narrow lily
gray mural
swift falcon
#

it does print out

gray mural
gray mural
#

just drag

#

I have downloaded what you have sent and dragged it, everything works

narrow lily
#

what now? how do i use it

narrow lily
#

for me it doesn't

gray mural
simple egret
gray mural
#

i have not checked it, yeah, it does not

narrow lily
gray mural
#

just in the assets

narrow lily
#

i am trying to figure out a way to use the sprite sheet inside unity
no, there is no .png variant of it

ashen yoke
#

find fla to png converter

swift falcon
ashen yoke
#

maybe you can convert to some vector format

narrow lily
simple egret
ashen yoke
#

unity has vector sprite package but i dont know if it supports fla

gray mural
#

@narrow lily You should go to Adobe Flash (cause .fla) and export the file with another format like swf, .fxg, .png, .jpeg

gray mural
swift falcon
#

i m making a map

gray mural
#

let's see possible errors

swift falcon
#

i have a cursor that moves with WASD

narrow lily
#

so i do need flash

swift falcon
#

and i m going over another image

#

but no printing

#

and it has a boxColider2D and the correct tag

gray mural
#
  1. There is no collision (for example the Z posiion is not the same)

  2. One or both images do not have BoxColliders2D

  3. There is no image with Rigidbody

  4. BoxColliders are triggers (make them collisions or use OnTriggerEnter2D instead)

ashen yoke
#

20 second search

ashen yoke
gray mural
swift falcon
#

@gray mural i do not know if i did anything wrong but i tried everything but it doesnt seem to see any collsiion

#

i tried adding rigitbodys too

#

and i checked the Z position too

#

both the same

gray mural
swift falcon
#

oh

#

where tho

#

on the cursor?

gray mural
#

@swift falcon
paste this code:

private void OnCollisionEnter2D(Collision2D collisionInfo) 
{
    Debug.Log("There was indeed a collision");

    if (collisionInfo.transform.tag == "Shrine") 
    {
        Debug.Log("succesfully found shrine");
    }
}
swift falcon
#

ok

urban marsh
#

Hello everyone !
I am trying to create a spell for my 2D top-down game, where the player can create an energy beam that continuously damage enemies (think Disintegrate from Diablo 3). The beam is "single target" : it originates from the player, and ends where it hits an enemy, dealing damage to the enemy.
I was thinking of implementing it using 3 prefabs : a "head", a "body" and a "foot", so that I have the foot that stays near the player's position, the Head that stays near the enemy position, and the body that extends between the head and foot, using continuously-tiled sprites to repeat it and get a beam that adapts itself to its length.
I have a problem, though : I don't know how to handle it so that is a second enemy moves and hit the body part of the beam, the whole beam becomes shorter, and the head's position is now at the place where the second enemy is.
Do you guys have any advice on that ?

swift falcon
#

my brain has stopped working idk wh yits not working

gray mural
gray mural
quartz folio
#

that collider is marked as a trigger

gray mural
gray mural
quartz folio
#

it will not receive collision messages.

swift falcon
#

wai wha

quartz folio
swift falcon
#

still doesnt work even if i turn it off

gray mural
#

here:

  1. There is no collision (for example the Z posiion is not the same)

  2. One or both images do not have BoxColliders2D

  3. There is no image with Rigidbody

4. BoxColliders are triggers (make them collisions or use OnTriggerEnter2D instead)

gray mural
swift falcon
#

wha?

#

aaaaa

#

it somehow works now

#

oh ma gawd

gray mural
swift falcon
#

idk what i did but i repeated the 4th step u gave me

gray mural
swift falcon
#

well

#

tank you for helping me

#

:;)

simple egret
#

Basically, as I understand it, they want a Line Renderer

#

And a raycast to detect hits

urban marsh
prime sinew
#

RaycastHit will contain information on what you hit

urban marsh
#

oh, ok

desert shard
#

I have a grenade that casts an overlap sphere. I want to limit what can be grabbed by the sphere for performance concerns. Though the root of my enemies don't have a collider. only limbs (the component I want to grab is on the root).

I've made a layer called IDamageable on the root of my enemies. is it "normal" or "standard" to have a small collider inside the mesh of the root so that nothing can physically hit it, only the overlapsphere can grab it. to deal damage to the enemies?

heady iris
#

I've done similar things before, yeah.

#

I don't think you can create a "point" collider

#

so a trigger collider that's roughly proportional in size to the enemy would be reasonable

gray mural
#

Does somebody know my even with playBackgroundMusicCoroutine the "Changed BG Music" is printed 1-3 times when audioSource ends?

private Coroutine playBackgroundMusicCoroutine;
private void Update()
{
    // ...

    if (audioSource.isPlaying)
    {
        if (!changingTime) timeSlider.rawValue = (int)audioSource.time;

        ChangeTimeInputText();
    }
    else
    {
        if (playBackgroundMusicCoroutine == null)
        {
            print("Changed BG Music");
            playBackgroundMusicCoroutine = StartCoroutine(PlayBackgroundMusic());
            ChangeTimeSlider();
        }
    }
}
private IEnumerator PlayBackgroundMusic()
{
    audioSource.clip = backgroundMusic[UnityEngine.Random.Range(0, backgroundMusic.Length)];
    audioSource.time = 0f;
    audioSource.Play();

    yield return new WaitUntil(() => audioSource.isPlaying);
    playBackgroundMusicCoroutine = null;
}
heady iris
#

i wonder if it's taking a few frames to load the audio

gray mural
heady iris
#

does the behavior change after the music is loaded once?

gray mural
gray mural
heady iris
#

ah, but it shouldn't be running the coroutine twice, 'cos it sets playBackgroundMusicCoroutine

heady iris
gray mural
hexed pecan
#

Whats the purpose of that WaitUntil?

gray mural
#

so that that this part of code won't be called a few times:

print("Changed BG Music");
playBackgroundMusicCoroutine = StartCoroutine(PlayBackgroundMusic());
ChangeTimeSlider();
#

and it should work I guess ??

#

it doesn't though

quartz folio
#

I don't really get it, why would you wait until it's playing

#

you just called Play, surely it's playing

gray mural
quartz folio
#

but why are you waiting for that, and then immediately starting a new coroutine to play something else

quartz folio
#

"play some music"
"oh, I see you have started playing that music I asked for"
"play some music"

heady iris
#

if we work under the assumption that isPlaying is only true once the audio clip is actually loaded and playing, then this would be reasonable

swift falcon
#

how can i find an object in the game with a name? so i have a name stored in a variable and i wanna find an object with that name in the game how do i do that?

quartz folio
#

why would this be reasonable

heady iris
#

but, again, this is assuming that isPlaying doesn't immediately become true..

quartz folio
#

surely you would want to play something when it ends

gray mural
#
if (is playing music)
{
    do smth 
}
else
{
    if (bg coroutine is not being executed)
    {
        then we change it's clip
    }
}
heady iris
gray mural
#
private IEnumerator PlayBackgroundMusic()
{
    set clip

    wait until the clip is set
}
heady iris
#

if isPlaying is false, it tries to change tracks, but only if it isn't already trying to do that

swift falcon
quartz folio
#

Ah I see, this is truly a bizarre way of doing this though, and I suspect that the bizarre way it's set up is the issue

heady iris
#

have you checked that isPlaying doesn't immediately become true?

#

although, even if it did immediately become true, I wouldn't expect this code to malfunction

gray mural
heady iris
#

do you have a problem if you don't do the coroutine business?

#

if you just pick a random clip and start playing it in the else block?

gray mural
heady iris
#

does it try to change the clip many times?

gray mural
#

I have done the coroutine to fix the issue

gray mural
#

1 to 3 times

#

while it's loading

#

so it is changed within 3 frames

scarlet talon
#

Why don't you make your own booleans for this then?

quartz folio
#

it's weird to use the coroutine as a boolean to see whether the audio has begun playing, when you could just set a boolean when you play music and, not use a coroutine

gray mural
heady iris
#

playBackgroundMusicCoroutine is acting as as mutex

#

indicating that the coroutine is currently running, and that you should not try to start another instance of it

gray mural
gray mural
#

and I do not see any reason for it not to work

heady iris
#

it does seem correct to me

gray mural
heady iris
#

the only thing I can think of is

#

does isPlaying stay true when you ask to play the clip

#

but then become false as it starts loading the clip?

gray mural
heady iris
#

"correct" as in "only fires once"

heady iris
gray mural
heady iris
#

Update -> start coroutine -> play audio clip -> yield -> WaitUntil finishes because isPlaying is still true -> coroutine finishes -> isPlaying becomes false as the new clip loads

gray mural
heady iris
#

that's the hypothesis, at least

heady iris
#

maybe you should Stop() the audio source

#

see if that changes the behavior

#

i've never really relied on isPlaying for anything, so i wouldn't have seen this before

#

but i can believe it

gray mural
#

so I have done this:

yield return new WaitUntil(() => audioSource.time >= 0f);
playBackgroundMusicCoroutine = null;

but there is still the same issue

#

and that's really strange

heady iris
#

have you tried putting audioSource.Stop() before you call audioSource.Play()

gray mural
#

it's try it rn

heady iris
gray mural
#

oh.

#

haha

gray mural
#

this also does not work

heady iris
#

yes, but have you tried the thing I suggested...?

gray mural
heady iris
#

stop the audio source, maybe even log isPlaying before and after to make sure that does something

#

you should really be logging that already, so that we aren't just guessing at how it behaves

gray mural
#

like this?

private IEnumerator PlayBackgroundMusic()
{
    audioSource.Stop();
    audioSource.clip = backgroundMusic[UnityEngine.Random.Range(0, backgroundMusic.Length)];
    audioSource.time = 0f;
    audioSource.Play();

    yield return new WaitUntil(() => audioSource.isPlaying);
    playBackgroundMusicCoroutine = null;
}
heady iris
#

assigning time is unnecessary

#

but yes, that's what I was thinking of

gray mural
#

no, necessary

gray mural
heady iris
#

perhaps until it starts playing again

#

since Stop() makes it start playing from the beginning when you eventually call Play()

heady iris
gray mural
#
private IEnumerator PlayBackgroundMusic()
{
    audioSource.Stop();
    audioSource.clip = backgroundMusic[UnityEngine.Random.Range(0, backgroundMusic.Length)];
    audioSource.time = 0f;
    audioSource.Play();

    yield return new WaitUntil(() => audioSource.isPlaying);
    playBackgroundMusicCoroutine = null;
}
quartz folio
#

Well, I used the original code and it only prints once every time it plays

heady iris
#

i was about to go implement it myself

#

i feel like you have an external factor here

gray mural
#

!code

tawny elkBOT
#
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.

heady iris
#

slap some debug statements in there to find out what order things are happening in, and what the values are at each point

#

that will be a lot easier than spitballing

quartz folio
#

Why do you call PlayBackgroundMusic in Start without assigning the coroutine

arctic canopy
#

https://forum.unity.com/threads/unity-crashes-badly-during-run-time.1434310/
heya...so i have this issue which is mentioned clearly on the forum, but here's the briefing.

during run time, at a certain time (mentioned on the post), my unity engine stops responding...and ive to force quit it in task manager. i tried to export the game in hope that it was just an engine fault...but it still happenes... i think it is due to the code sucks... can anyone pls help me out? this was for a game jam... thx.

ps: i posted this thing in #archived-code-advanced 'accidently', and they said to debug it (like adding a breakpoint, still nope, it crashes badly)

gray mural
heady iris
#

because the whole point is that you use that variable as a mutex

#

you must never have more than one instance of that coroutine at once, right?

heady iris
#

have you actually verified that isPlaying doesn't become true (and stay true) after calling Play?

quartz folio
heady iris
#

if not, all of this is pointless

gray mural
heady iris
#

you cannot fix a problem that you do not understand

arctic canopy
#

oh

heady iris
#

it may take more than "one sec" to properly test this

#

you must convince yourself

quartz folio
#

Well, the code definitely works fine for me. I'm not using your whole thing though as I cbf setting all this up

#

I can only imagine there's a few instances of the script or something

#

or some other random logic error interfering with things, like manipulating the audio source from another script

heady iris
#

or something else is--

#

yeah

scarlet talon
#

Print something in start and see if it shows more than once

heady iris
#

and, generally, do some diagnostic work

heady iris
#

does it STAY true?

#

that is the million dollar question right now

gray mural
#
audioSource.Play();
print($"audioSource.isPlaying: {audioSource.isPlaying}");
#

that's extremely strange

heady iris
#

if it stays true, even as the audio clip gets loaded, then you are barking up the wrong tree

#

the problem is somewhere else

quartz folio
#

Strange, but exactly as I expect lol

gray mural
#

I am sorry @heady iris @quartz folio

heady iris
#

understand the problem before you attack it (:

gray mural
#

lemme change it to the void I guess

swift falcon
#

how can i make unity wait for example like this


  Debug.Log("example")

  //Wait 2 Seconds

  Debug.Log("Done Waiting")

gray mural
#
private void Update()
{
    if (audioSource.isPlaying)
    {
        if (!changingTime) timeSlider.rawValue = (int)audioSource.time;

        ChangeTimeInputText();
    }
    else
    {
        print("Changed BG Music");
        PlayBackgroundMusic();
        ChangeTimeSlider();
    }
}
private void PlayBackgroundMusic()
{
    audioSource.clip = backgroundMusic[UnityEngine.Random.Range(0, backgroundMusic.Length)];
    audioSource.time = 0f;

    audioSource.Play();
    print($"audioSource.isPlaying: {audioSource.isPlaying}");
}

I now have this and it always prints that audioSource.isPlaying is true. Still it is executed a few times.

#

and the GM with audioSource does also have DDOL script

magic parrot
#

!code

tawny elkBOT
#
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.

magic parrot
#

Hi there, just interested if anyone had this problem before.

In unity, my game has not compiler errors, and everythings running as it should, but when I exported to a webgl build some of the coroutines didn't work at all
If you want to test the game for yourself and see the problem accures when entering a wild battle, here's the game link : https://jeffrygames.itch.io/hexmone

itch.io

Play in your browser

leaden ice
#

neither of which are guaranteed

magic parrot
#

thank you, ill check it

#

it gave me at least a idea of what to check

gray mural
#

@magic parrot I thikn you have lot's of issues with colliders in your game

magic parrot
#

What do you mean?

gray mural
magic parrot
#

"That's not a bug, thats a feature" kind of thing

gray mural
magic parrot
#

the wall thingy is, i am not sure what do you mean by walking between doors

#

if you mean the doors dont react, you need to press space or j to interact with them @gray mural

gray mural
magic parrot
#

its complicated...

#

I'm not sure how to explain the reason

gray mural
magic parrot
#

thats on purpose

gray mural
# magic parrot its complicated...

just use

if (Input.GetKey(KeyCode.W))
{
    // ...
}
if (Input.GetKey(KeyCode.S))
{
    // ...
}
if (Input.GetKey(KeyCode.D))
{
    // ...
}
if (Input.GetKey(KeyCode.A))
{
    // ...
}
gray mural
magic parrot
rigid moon
#

i was investigating sudden lag spike after implementing a feature and it just editor loop taking up 95% of the usage, this should be fine to ignore right?

magic parrot
#

oh my, thats not good

rigid moon
#

its weird tho, my playerloop don't have anything executing for that long

urban marsh
#

Hello again guys !
I am using a Physics2D.Raycast to check how far an enemy is in a script of mine, following advice from this channel.
The raycast seem to find Trigger-colliders and Normal-colliders, even though I want only trigger-colliders.
I found the alternative signature public static int Raycast(Vector2 origin, Vector2 direction, ContactFilter2D contactFilter, RaycastHit2D[] results, float distance = Mathf.Infinity); which should let me filter to only Normal-colliders using the ContactFilter2D, but it uses an array of results. Reading the doc, it doesn't tell me, even though I think it's the most important point of the Raycast :
Is the array of results ordered by distance from the raycast's point of origin ?

magic parrot
#

you should not use mathf.infinity for that

#

that will be very lagy

leaden ice
#

if you only want the first hit, don't use the multiple/array version

#

just use the version that returns a single hit

rigid moon
#

nvm something just choke the editor, restarted the editor its fine now

urban marsh
#

why isn't there a "normal" way of using it (with the public static RaycastHit2D Raycast(Vector2 origin, Vector2 direction, float distance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, float minDepth = -Mathf.Infinity, float maxDepth = Mathf.Infinity);signature) that let you use only normal-colliders ?

urban marsh
#

my visual studio code tells me it doesn't exists :/

#

or rather, it didn't show it to me in the list of potential signatures when writing the beginning of the call, and when writing it totally, it gives me an error telling me that it "can not convert from ContactFilter2D to int" (because there is another signature with an int instead of the contactFilter2d)

simple egret
#

Yeah you need a PhysicsScene2D instance to have access to the linked method

#

Not sure how and where to get one

urban marsh
#

I do not understand a word you're saying :/

gray mural
#

@magic parrot sorry, how to leave or play?

urban marsh
#

what are PhysicsScene2D and the difference with Physics2D ?

leaden ice
#

Physics2D just does things in the default (single) physics scene

#

if you're using multi scene physics you need to specify which physics scene you want to do queries in - hence the PhysicsScene2D object

urban marsh
#

how do I get the physicsscene2D instance from my scene to do the raycast on ? (on a simple game)

leaden ice
#

Sorry I didn't realize the method I linked was only on PhysicsScene2D

#

seems like an oversight on Unity's part to not backport that into Physics2D

urban marsh
#

if I have a game with multiple scene, and load another scene when I change level, should I use this default thing ?

leaden ice
#

as long as you're not using multiple physics scenes it doesn't matter how many scenes you load

#

there's only the default physics scene

urban marsh
#

It worries me that it will work right now in testing because I only have 1 scene while debugging, but it won't work later when the player can win a level and go to another one :p

leaden ice
#

you would know if you were using multiple physics scenes