#💻┃code-beginner

1 messages · Page 30 of 1

low perch
#

its weird it retunrs null still

violet topaz
#

@rich adder ok im back and it work but it only shoots up

rich adder
rich adder
#

what worked

topaz mortar
#

how would I check if this returns an object of type Item instead of just checking if it's not null?
if (_head.GetComponentInChildren<Item>() != null)

rich adder
slender nymph
#

another thing to note is that being able to just yield an IEnumerator method call instead of being required to use StartCoroutine to wait for a nested coroutine to complete wasn't always possible

low perch
rich adder
violet topaz
#
void Shoot()
    {
        GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
        Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
        firePoint.transform.rotation = Quaternion.Euler(0f, 0f, Random.Range(-10f, 10f));
        rb.AddForce(firePoint.up * bulletForce, ForceMode2D.Impulse);


    }``` i changed ```cs
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, Quaternion.identity);``` to ```cs
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);```  and ```cs
firePoint.transform.rotation *=``` to ```cs
firePoint.transform.rotation =```
rich adder
#

I never used IEnumerator outside unity context tbh

low perch
slender nymph
rich adder
#

pretty neat, I'm gonna look into it just curious 😅

rich adder
tulip tapir
#

im trying right now ur Idea, but what do i do for mp3?
he tells me
UnityWebRequestMultimedia.GetAudioClip(path, AudioType.mp3)
does not work
because
'AudioType' does not contain a definition for 'mp3'

low perch
rich adder
#

spelling matters

#

your IDE is not configured is it..

#

you would see entire enum list when you do .

barren vapor
#

Configured to the database and stuff. Let's test out if mister chatgpt is correct

tulip tapir
low perch
gray arrow
#

Hey guys, im trying to get a mesh to correctly align with the player when aiming down sights, however when I walk away from the origin the rotation gets really messed up. can one of you guys take a look at my code and see what i'm doing wrong? (ill send the code as a seperate message if i can, its quite long and above the limit)

and here is a short video to demonstrate the issue:

#

here is the code:

private void LateUpdate()
    {   
        var mouse_pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        mouse_pos.z = 0f; 

        print(mouse_pos);

        startingAngle = Mathf.Atan2(mouse_pos.y - transform.position.y, mouse_pos.x - transform.position.x) * Mathf.Rad2Deg;

        print(startingAngle);
        int rayCount = 600;
        float angleIncrease = fov / rayCount;
        float angle = startingAngle + (fov/2);

        Vector3[] vertices = new Vector3[rayCount + 1 + 1];
        Vector2[] uv = new Vector2[vertices.Length];
        int[] triangles = new int[rayCount * 3];

        vertices[0] = origin;

        int vertexIndex = 1;
        int triangleIndex = 0;
        for (int i = 0; i <= rayCount; i++)
        {
            Vector3 vertex;
            RaycastHit2D raycastHit2D = Physics2D.Raycast(origin, GetVectorFromAngle(angle), viewDistance, layerMask);

            if (raycastHit2D.collider == null) {
                // no hit
                vertex = origin + GetVectorFromAngle(angle) * viewDistance;
            } else {
                //hit Object
                vertex = raycastHit2D.point;
            }

            vertices[vertexIndex] = vertex;

            if (i > 0)
            {
            triangles[triangleIndex + 0] = 0;
            triangles[triangleIndex + 1] = vertexIndex - 1;
            triangles[triangleIndex + 2] = vertexIndex;

            triangleIndex += 3;
            }

            vertexIndex++;

            angle -= angleIncrease;
        }

        mesh.vertices = vertices;
        mesh.uv = uv;
        mesh.triangles = triangles;
        mesh.bounds = new Bounds(origin, Vector3.one * 1000f);

        if (Input.GetKey(KeyCode.Mouse1))
        {
            fov = 60;
        }
        else
        {
            fov = defaultFov;
        }
    }
rich adder
#

but also you can just cast the bullet as a rigidbody2D

Rigidbody2D bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);

#

and skip the GetComponent

low perch
rich adder
tulip tapir
#

@rich adder Hey Honey, your Idea worked, at least in the Editor yet, get a digital Hug
:-]
ill try now on windows and mac, if that works aswell, imagine 2 more ;)

rich adder
#

just make sure you're using the correct paths lol

violet topaz
#

@rich adder i get this error Error CS0029 Cannot implicitly convert type 'UnityEngine.GameObject' to 'UnityEngine.Rigidbody2D' on cs Rigidbody2D bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);

summer stump
rich adder
#

yeah this sry

#

forgot to mention that

#

😅

#

might need to drag the prefab back inside the slot after

#

or unity gives a Mismatch

violet topaz
#

@rich adder

tender stag
#

what do you mean

ashen ferry
#

did bro just shot himself and died kekW

tulip tapir
rich adder
rich adder
violet topaz
#

its the rotate line

rich adder
rich adder
violet topaz
#

yep

tulip tapir
rich adder
tulip tapir
rich adder
#

and which folder location are you using

tulip tapir
rich adder
# violet topaz yep

var rot = firePoint.transform.eulerAngles; rot.z += Random.Range(-10f, 10f); firePoint.transform.eulerAngles = rot; i think

rich adder
#

you should be using Application.persistentDataPath

#

forget about the whole Resource thing too tbh

tulip tapir
tulip tapir
tulip tapir
# rich adder bruh

macOS player uses Application.dataPath + "/Resources/Data/StreamingAssets"
it said ...

queen adder
#
using Unity.Services.Core;
using Unity.Services.Economy;
using Unity.Services.Economy.Model;
using UnityEngine;

public class Economy : MonoBehaviour
{
    string slurpCoins = "SLURP_COINS";
    
    private async void Start()
    {
        await UnityServices.InitializeAsync();
        await EconomyService.Instance.Configuration.SyncConfigurationAsync();

        GetBalance();
    }

    private async void GetBalance()
    {
        CurrencyDefinition slurpCurrencyDefinition = EconomyService.Instance.Configuration.GetCurrency(slurpCoins);
        PlayerBalance playersSlurpCoinsBalance = await slurpCurrencyDefinition.GetPlayerBalanceAsync();

        if (playersSlurpCoinsBalance != null)
        {
            Debug.Log($"Player's balance: {playersSlurpCoinsBalance.Balance}");
        }
        else
        {
            Debug.LogError("Failed to get player's balance.");
        }      
    }
}

Am I doing this correctly?

rich adder
tender stag
#

so that i'll be able to use item.durability for example

#

item being this

tulip tapir
#

so i tried this
persistentDataPath
but then i get an error with the www thing

tulip tapir
timber tide
tender stag
#

yeah

violet topaz
#

@rich adder i have to go but it goes in the right direction but doesnt start in the right angles

slender nymph
rich adder
tender stag
#

not just weapon

timber tide
#

Maybe consider interfaces

#

and check if it has an interface of durability

ashen ferry
#

he can cast

#

into WeaponItem

tender stag
#

but its going to be a lot more

timber tide
#

yeah but if he has a lot of different items of durability

tender stag
#

like 10

timber tide
#

weapon casting would fail on everything else

tender stag
#

im not gonna cast and check like 10 things

ashen ferry
#

oh yea like equipment items etc

tender stag
#

thats pointless

ashen ferry
#

mb

tender stag
#

consumable items

#

also

tender stag
#

or should i just put the durability into item?

ashen ferry
#

then you could make Ibreakable interface and if item implements it that means it has durability

tender stag
#

and save myself a lot of time

rich adder
ashen ferry
#

idk tbh this class hierarchy thing is hard asf for myself but I got burned putting too much stuff into base class once XD

tender stag
#

Mao what do you think

#

would it just be best at this point to just put it into Item?

timber tide
#

Well, that means everything has durability then

tender stag
#

but then i can check like i did before

timber tide
#

True

tender stag
#

if the maxDurability is above 0

#

that means its using durability

rich adder
#

much more modular

queen adder
ashen ferry
#

yea but so much more code

#

thats not the problem now in hindsight

#

but was main reason why I didnt like them bruh

rich adder
#

much more code happens when your code is not split into single responsibility

#

usually

tender stag
#

combination between both is best for me

tulip tapir
queen adder
#

Adding, removing curre by completing certain tasks in the future

rich adder
queen adder
#

Okay thanks thats why i asked cus i wasnt sure what should be called first, etc

rich adder
#

this way as long as that sevice is started, any other service like Economy will work fine

#

or if you need to login a user

queen adder
#

if i started it in another script before this scene do i need to do it again?

rich adder
#

but im not 100% on that

#

I can test it later or you can try it or sum

queen adder
#

yea il look

rich adder
#

it will work but not well

#

it will just spawn bullet as child of pTrans

#

no specific position / rotation . just where pTrans is , as its child

wintry quarry
#

if there is no log, the code is not running

#

it's not runniung

#

or the log would print

#

(I mean the code inside the if statement)

#

you are missing cs gamepadRight.action.Enable();

#

need to do that in Awake or Start or something

tulip tapir
wintry quarry
tulip tapir
wintry quarry
#

as said before, you made the bulklet a child of pTrans. so... it's acting like a child

queen adder
#

Is there a method for Unity.Services.Authentication; that u can use to sign out

wintry quarry
rich adder
#

depends on how you sign them in

gray arrow
#

Hey guys, im trying to get a mesh to correctly align with the player when aiming down sights, however when I walk away from the origin the rotation gets really messed up. can one of you guys take a look at my code and see what i'm doing wrong? (ill send the code as a seperate message if i can, its quite long and above the limit)

and here is a short video to demonstrate the issue:

#
private void LateUpdate()
    {   
        var mouse_pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        mouse_pos.z = 0f; 

        print(mouse_pos);

        startingAngle = Mathf.Atan2(mouse_pos.y - transform.position.y, mouse_pos.x - transform.position.x) * Mathf.Rad2Deg;

        print(startingAngle);
        int rayCount = 600;
        float angleIncrease = fov / rayCount;
        float angle = startingAngle + (fov/2);

        Vector3[] vertices = new Vector3[rayCount + 1 + 1];
        Vector2[] uv = new Vector2[vertices.Length];
        int[] triangles = new int[rayCount * 3];

        vertices[0] = origin;

        int vertexIndex = 1;
        int triangleIndex = 0;
        for (int i = 0; i <= rayCount; i++)
        {
            Vector3 vertex;
            RaycastHit2D raycastHit2D = Physics2D.Raycast(origin, GetVectorFromAngle(angle), viewDistance, layerMask);

            if (raycastHit2D.collider == null) {
                // no hit
                vertex = origin + GetVectorFromAngle(angle) * viewDistance;
            } else {
                //hit Object
                vertex = raycastHit2D.point;
            }

            vertices[vertexIndex] = vertex;

            if (i > 0)
            {
            triangles[triangleIndex + 0] = 0;
            triangles[triangleIndex + 1] = vertexIndex - 1;
            triangles[triangleIndex + 2] = vertexIndex;

            triangleIndex += 3;
            }
            
            vertexIndex++;

            angle -= angleIncrease;
        }
queen adder
#

I assume this does not have it

wintry quarry
gray arrow
solar berry
#

how do I make the animation not start from the beginning of the scene?

tender stag
#

i made the interface

rich adder
wintry quarry
#

why are you doing angle * (Mathf.PI/180f);

timber tide
wintry quarry
#

if you want to convert to radians just do float angleRad = Mathf.Deg2Rad * angle;

tender stag
gray arrow
rich adder
wintry quarry
tender stag
rich adder
tender stag
#

like this?

wintry quarry
#

but also just use Mathf.Rad2Deg

gray arrow
wintry quarry
#

the fucntion is definitely wrong

tender stag
#

and do this?

wintry quarry
#

pretty sure you copied it wrong @gray arrow

gaunt thistle
#

trying to compile my game, wont compile says its importing

#

when its not

#

tried restarting

#

nowt

gray arrow
wintry quarry
#

then you probably also have another issue elsewhere

queen adder
wintry quarry
#

using an incorrect conversion isn't going to make things work well

tender stag
# timber tide Yep

then i can do something like this?cs if(selectedCell.item && (selectedCell.item as IDurable).Durability > 0)

queen adder
#

alright

tender stag
# tender stag

@rich adder sorry to ping u but i wanna make sure i got this correct

gaunt thistle
gray arrow
wintry quarry
#

I don't trust you because you started out with a wrong conversion from degrees to radians

rich adder
timber tide
ashen anchor
#

Hey may someone help me
Im trying to do a Wave System where every 3 seconds a balloon spawns. The problem is unity spawns unlimited Balloons. Please help

tender stag
#

so im doing it correctly?

wintry quarry
timber tide
#

Try it :)

ashen anchor
#

How can i send it as an Code?

wintry quarry
gray arrow
wintry quarry
tender stag
#

this is what i got

timber tide
#

nice, but did you test it in game

ashen anchor
#
using System.Collections.Generic;
using TMPro;
using UnityEngine;

public class GameController : MonoBehaviour
{
    [HideInInspector]
    public List<GameObject> Balloons = new List<GameObject>();

    public GameObject Balloon;
    public GameObject Monkey;

    public TextMeshProUGUI ScoreText;
    public TextMeshProUGUI CoinsText;

    internal int Score = 0;
    internal int Coins = 120;

    internal int MonkeyPrize = 100;

    int WaveCounter = 1;
    bool IsWaveActive;

    void Start()
    {

    }

    void Update()
    {
        ScoreText.text = Score.ToString();
        CoinsText.text = "Coins: " + Coins.ToString();

      

        if(WaveCounter == 1 && !IsWaveActive)
        {
            Wave1(10);
        }

    }


    void Wave1(float WaveTimer)
    {
        while (WaveCounter == 1)
        {
            if (WaveTimer > 0)
            {
                IsWaveActive = true;
                StartCoroutine(SpawnBalloons(Balloon, 3));
                WaveTimer -= Time.deltaTime;
            }
            else
            {
                IsWaveActive = false;
                WaveCounter += 1;
            }
        }
 
    }


    // Balloons spawnen und zur Liste "Balloons" hinzufügen
    IEnumerator SpawnBalloons(GameObject Balloon, float WaitForSec)
    {
        while (IsWaveActive)
        {
            GameObject NewBalloon = Instantiate(Balloon);
            Balloons.Add(NewBalloon);
            yield return new WaitForSeconds(WaitForSec);
        }

    }
#

There are many things taken out. They are not important for the problem

wintry quarry
#

what are the vectors being produced

#

that's where you need to start

#

figure out where things go off the rails

gray arrow
#

things work near 0,0

#

but as you walk away they get bad

#

i think its to do with the mouse position being mapped to the world one

wintry quarry
ashen anchor
buoyant knot
#

If I have a block on a block on a block, and they are all dynamic, is there a way for me to stop the thing on the middle from being affected by the one on the top?

wintry quarry
ashen anchor
buoyant knot
#

I have to wonder if I would be better served by kinematic RBs for everything; but I don’t know how to manage basic collision with walls

wintry quarry
#

which is probably not correct

tulip tapir
ashen anchor
ashen anchor
rich adder
#

probably something to do with HTTP? areyou still using that or streamingassets

#

now im confused

tulip tapir
# rich adder which line which one ?

the Ingame Console you send me, gave me this notification (white), not as an error, but i think, that will be the problem.
ae you sure UnityWebRequest works on mac in the same way as on windows?

rich adder
tulip tapir
ashen anchor
wintry quarry
tulip tapir
wintry quarry
#

your code was a little confusing so it's hard to see

rich adder
#

ohh wops my mistake that also confused me

ashen anchor
timber tide
# tender stag

should probably make sure you're checking if item IS IDurable cause otherwise it will return null

#

I think you can just inline it there and get a reference? I forget

tulip tapir
#

Noone has an Idea?
I want to use
UnityWebRequestMultimedia.GetAudioClip(path, AudioType.MPEG)
to load an mp3 from my streaming asset folder for my Audiosource but i get the Error
"cannot connect to destination host"
what happens?

timber tide
#
if(item != null && item is IDurable durable) {}```
tender stag
#

i realised a minute ago

#

i did the same thing

#

works great thank you so much

timber tide
#

ye np

tulip tapir
# wintry quarry What path did you provide

Application.streamingAssetsPath

i now check chinese forums, cause it seems like they have the same problem xD
https://blog.csdn.net/Ailegen/article/details/105579247

wintry quarry
# tender stag

you can make this a little cleaner:

if (item is IDurable durableItem) {

}```
wintry quarry
tender stag
#

i can also now use interfaces for other specific item stats

#

if im going to have any

tulip tapir
wintry quarry
#

since UnityWebRequest expects a URI

timber tide
#

You still have to check the null though, no? Or will that not throw an error

tender stag
#

i thought it would

tulip tapir
tender stag
#

it doesnt

swift crag
#

(possibly user-provided, hence being in StreamingAssets)

wintry quarry
#

Yeah I got that part

#

although StreamingAssets isn't really the place for user provided files

#

it's the place for verbatim files from the project itself

swift crag
#

i guess there's no reason for them to be in that folder in particular

#

since they just need to exist, somewhere

#

i hadn't actually thought about the point of that directory before

rich adder
#

I did suggest earlier, at that point just use WebRequest + Application.persistentDatapath

#

dont think streamingasset is needed

#

chances are you're not passing the firepoint as spawn location @queen adder

#

hmm somehow they move as if they were parented to object

#

hard to say without seeing script

#

what does bullet scrit look like

#

hmm

polar acorn
#

Show the inspector for the bullet prefab

turbid robin
#

This is a step in the unity tutorial tha i am watching, i dont find the section "add modules", were can i find it in unity hub?

turbid robin
#

oh thx

#

sorry i didnt see the video

#

yeah sorry, i read from up to down

#

so i respond to the first message and after to the second

#

i dont have that

rich adder
turbid robin
#

2021

rich adder
#

that aint the issue, they have installed unity Manually

violet topaz
#

@rich adder I will be back in 20 minutes

rich adder
#

with what ?

#

I thought u were sending bullet script

#

so bullet has no script

#

why do you have gravity in a topdown

#

set the Gravity scale to 0

#

it could if it hits colliders.

#

its an active physics object

#

ofc its gonna move

#

try without it or set it to kinematic

#

also your in Center pivot mode

#

not probably what you want to set up correct pivots

#

thi should be on Pivot / Local

#

it migt not even be spawning from where u think its spawning

#

yes

#

now make sure spawn points are where they need to be with correct rotations too

#

uh this wasnt a fix

#

which gameobject has BulletSpawn

#

screenshot it

#

with pivot selected

unreal imp
#

guys im trying to access the parent´s rigidbody of my object but this doesnt works,heres the code ```if (col.CompareTag("Toilet"))
{
Vector3 direction = col.GetComponentInParent<Rigidbody>().position - transform.position;
var m = col.GetComponentInParent<Rigidbody>();

            float distance = direction.magnitude;
            float forceFactor = 1f - (distance / explosionRadius);
            float appliedForce = explosionForce * forceFactor;
            m.AddForce(direction.normalized * appliedForce, ForceMode.Impulse);
            var v = col.gameObject.GetComponent<ToiletBehaviour>();
            v.isInFire = true;
        }```
rich adder
#

its not

#

show me with pivot selected

#

the MoveTool shows the pivot

#

select the movetool first

graceful flicker
#

when I create item system using classes, where and how do I save a list of all possible items? do I have to create a c# script with a list of all items and its settings?

rich adder
#

ok the rotation at least is fdup , not sure why the position is wrong still though

#

thats cause you use Quaternion.identity

compact dirge
#

so, i have a class Entity with a child class Enemy
How can i know what Entity into a list are Enemy?

tulip tapir
rich adder
#

no, but is your thing moving at all ?

#

spawn point

surreal wagon
#

im extremely new to unity

#

i there any way to program using primarily c++ in it?

frosty hound
#

No, it's C# only

surreal wagon
#

aw man

#

is there like some sort of plugin that can convert a c++ script to a c# script?

frosty hound
#

Likely not

rich adder
surreal wagon
#

i get that but learning another language is just a hassle

sour fulcrum
#

Also, With Unity, Godot, Roblox and more utilising C#, It's a really valuable language to pick up

rich adder
modest dust
#

Although I didn't learn C# when I started Unity

surreal wagon
#

my pc cant run unreal 😿

modest dust
#

C++ similarities were enough to do most of the simple stuff

surreal wagon
#

where can i learn c#

rich adder
ripe shard
surreal wagon
#

thanks

ripe shard
#

best of luck

turbid robin
#

"On the left of the Unity Hub window, select the Installs tab.

Select the Add button."
were is add? i dont see it

surreal wagon
#

idek

rich adder
#

also why are u reposting it inside a code channel

turbid robin
#

i am following a link that someone sendend me and they literlaly said to follow it

turbid robin
polar acorn
turbid robin
violet topaz
#

@rich adder are you here

rich adder
violet topaz
#

oh and the problem is that fire point is going all over and not resetting

analog bridge
#

Hi there! Does any one could help with a FPS that can move just with key forward and backyard and rotation left right (I have the code for the movement) with the collision? It's been 1 week I am trying to ads collision to my player.

rich adder
#

youd have to do some sort of timer / coroutine to snap back to original @violet topaz

#

it would be too instant without some smoothing but still doable

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.

analog bridge
summer stump
analog bridge
#

I see, let me try

pearl grotto
#

I have never seen the ? operator in C# can someone explain to me this call one of my friends just submitted to our project's main branch? it seems to work i just don't understand it

#

equippedWeapon.Fire(aiming ? equippedWeaponScope.GetMultiplierSpread() : 1.0f);

violet topaz
#

@rich adder could i do if the firepoints rotation is > 10 and it resets back to zero

analog bridge
summer stump
pearl grotto
#

neat, is it any more efficient(at runtime not in terms of characters obviously)?

rich adder
summer stump
violet topaz
#
if(rot.z > 10f  rot.z < -10f)
        {
            rot.z = 0f;
        } ``` how do i do "or"
rich adder
#

you need to store the rotation before applying the Random offset @violet topaz

#

then apply it back

pearl grotto
violet topaz
rich adder
#

you're teleporting essentially

#

you want a character controller at very least

analog bridge
analog bridge
#

I don't want to use the mouse to move the camera

rich adder
analog bridge
#

Thanks for the links!

#

I don"t know yet where to start

#

but hopefully Ill be able to add the missing code for the collision

analog bridge
#

Thanks you so much!

compact dirge
#

how can i pass a class by value instead of by reference?

violet topaz
#

@rich adder so you think a timer is the best way to fix my problem?

rich adder
rich adder
summer stump
rich adder
#

ima take a wild guess, something to do with multiplayer xD

analog bridge
compact dirge
#

but anyway
i can still copy that class variable into a new one created with new() and i should be fine, right?

rich adder
compact dirge
# rich adder what is it you need to do this for?

so, when i do an attack in my game, i collect some info into a class called AttackData.
The Attack is a class (stored into a variable of enemy or player class) that contain some info, and i must pass an Attack into the method CollectAttackData. In this method, the Attack itself will be added to the AttackData infos as a variable.
The problem is that, later, i must manage and change some values of the Attack into the AttackData. But i don't want to change the value into the original Attack variable, that is still into a player/enemy

open vine
#

Hey, can someone help me with why my overlapsphere is getting every collider but my Player? im setting an array of colliders to the overlapsphere and then foreach collider in the array i debug the name but it never gets my player no matter how big the radius

rich adder
#

or wouldn't attack just hold a struct for its data

rich adder
compact dirge
rich adder
open vine
rich adder
#

just store the struct of data

compact dirge
#

but i can't do a struct cause Attack is a class with some child class

#

and i need to pass the entire attack at the attackdata

rich adder
compact dirge
#

i mean maybe i can create a struct into attack and just trhow all the infos of the attack into it..?

compact dirge
#

and afaik struct can't have something like child class

compact dirge
rich adder
# compact dirge maybe thats's what do you mean?
public class Attack : MonoBehaviour
{
    public AttackData attackData;
}
[Serializable]
public struct AttackData
{
    public int Data1;
    public string Data2;
    public float Data3;
}``` 

Only need to store AttackData no ?
#
 [SerializeField] private List<AttackData> attackData;
    [SerializeField] private List<Attack> attacks;
    private void Awake() => attacks.AddRange(FindObjectsOfType<Attack>());
    private IEnumerator Start()
    {
        yield return new WaitForSeconds(2);
        foreach (Attack attack in attacks)
        {
            attackData.Add(attack.attackData);
        }

        for (int i = 0; i < attackData.Count; i++)
        {
            var ada = attackData[i];
            ada.Data2 = "Hellooooooooo";
           attackData[i] = ada;
        }
    }```
compact dirge
rich adder
#

idk working with reference types is annoying sometimes with that

compact dirge
rich adder
#

all your doing is passing around copies of the same pointer

compact dirge
#

I will see tomorrow. Thanks!

queen adder
#

How can i make remember me check box for login using UGS with name and password identity

rich adder
queen adder
#

without storing the login in prefs or locally

summer stump
#

Or some data locally

rich adder
#

and also they dont store login

#

its a session token

queen adder
idle palm
#

https://paste.ofcode.org/4CTDzchhHWhbyKVZ2wnL4n

I don't know what I did wrong here. There are console errors:

Assets\SceneManager.cs(10,22): error CS0117: 'SceneManager' does not contain a definition for 'LoadScene'

Assets\Scenes.cs(10,22): error CS0117: 'SceneManager' does not contain a definition for 'LoadScene'

I looked through it on the forums they said to not have the public class set to SceneManager, however I changed it to Scenes along with the script name but it still does not work.

wintry quarry
#

Which is apparent from:

Assets\SceneManager.cs(10,22): error CS0117: 'SceneManager' does not contain a definition for 'LoadScene'

rich adder
#

ah rip

wintry quarry
#

it's trying to use YOUR class instead of Unity's

rich adder
#

didnt even notice script name lmfao

wintry quarry
#

you can fix this by doing UnityEngine.SceneManagement.LoadScene - or by renaming your class, or with a using SceneManager = UnityEngine.SceneManagement.SceneManager;

idle palm
wintry quarry
#

the old one still exists

#

hence that first error

idle palm
idle palm
summer stump
#

The way you have it written wouldn't work, it would still be ambiguous

#

It might show a different error though

rich adder
#

you shouldn't have to worry about it tbh just call your script something else lmao

idle palm
summer stump
#

Yeah, never name a class the same thing as a built in class unless you REALLY know what you're doing and know your way around namespaces. And even then, probably don't

rich adder
#

unless you still got compile error lol

idle palm
idle palm
rich adder
summer stump
#

Did you delete the SceneManager script you had?

idle palm
summer stump
#

Ok, show a screenshot of showing the buttons inspector

summer stump
rich adder
summer stump
#

Not an object

idle palm
summer stump
#

It would show "(objectName)"

Unless I'm misremembering

rich adder
idle palm
slender path
#

how do you get the height of a mesh at a certain point

rich adder
slender path
#

I have tried, i might have done it wrong so how would you do it

rich adder
unreal imp
# polar acorn What "doesn't works"

Sorry for responding late, I'm doing that if my object is close to an explosion it moves a little but the thing that doesn't work is because the collider is in the child object (the object is already selected) and the rigid body in the parent

slender path
wintry quarry
rich adder
#

are you getting error

slender path
#

it won't get the point, it just gets the mesh position

summer stump
#

Have you tried just raycasting down and getting the position of the raycastHit?

wintry quarry
#

Note this is Collider.Raycast, not Physics.Raycast

rich adder
#

wowz colliders can raycast

#

TIL

summer stump
#

Wait wtf! That is awesome!

#

I wish I knew about that sooner

slender path
#

I have tried regular raycasting and it returns a distance of zero
I have not gotten collider.Raycast to work
i have tried physics.raycast as well

summer stump
#

Why get distance? You want the point

#

And you tell it the distance to go

slender path
#

that did not work either

rich adder
#

should also do Gizmos.DrawSphere(closestPoint, 0.1f);

wintry quarry
#

is the sphere inside the mesh?

summer stump
wintry quarry
#

is it above the mesh?

#

What exactly is going on here

slender path
#

it is above the mesh

#

should it be below

wintry quarry
#

What kind of mesh is it

#

is it a plane?

#

some complex shape?

slender path
#

meshObject = new GameObject("Terrain Chunk(" + regionX + ", " + regionY + ")");

wintry quarry
#

that tells me nothing about the mesh

#

that's just a GameObject

#

an empty one at that

slender path
#

!code

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.

slender path
#

it gets assigned its components at line 55

summer stump
#

Where do you add the mesh?

#

Those are just empty components it looks like

summer stump
#

@slender path Can I get some context for those massive dumps of code? On a quick look, it seems like you don't add the mesh anywhere between line 55 and 66 on that first script?

acoustic arch
#

for a simple 2D top down game, should i use transform.Translate, rb.MovePosition er whats best

rich adder
wintry quarry
#

neither of those will give accurate collisions

#

If you want proper collision handling you must move via modifying Rigidbody velocity or by adding forces (which modifies rigidbody velocity)

acoustic arch
#

as long as the collisions are ok its fine

wintry quarry
acoustic arch
#

this game is more of an animation learning process

acoustic arch
wintry quarry
#

depends what you mean by "accurate"

#

lots of games don't require physics at all. For example grid based games

rich adder
wintry quarry
#

yes it can but kinematic aren't affected by collisions with anything

rich adder
#

oh yeah it probably does ray/physics casts for collisions

solid cove
#

see above, i'm following a tutorial for 2d movemen, but for some reason my character always gets triggered by a collision i cant discover.

#

as you see in the video the layers are correctly placed, and character movement is smooth, except for some certain spots where it gets stuck

#

would be apprecated with any feedback

rich adder
#

show ContactFilter2D values

random ether
#

Ok so Im trying to make a system where these "obstacles" spawn along a road at random points on that road. For some reason when I run this script on an empty object (properly assigning the public variables), the obstacles only spawn on one point.

#

does anyone know how to fix this

#

I even tried this simplified version but it still wont spawn in diff places.

#

Note: i used a sprite (which is a long rectangle) as the road, assuming that the objects spawn along that road

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.

topaz mortar
random ether
normal yoke
#

Im not sure if this is the right channel but Im dying for some help!

Im trying to open a unity package file of a vtuber but it wont open? or at least when i import I see absolutely nothing does anyone know how to fix this?

topaz mortar
summer stump
normal yoke
topaz mortar
summer stump
normal yoke
#

also there is a thing saying for me to check external application preferences and its unable to open the asset

normal yoke
summer stump
normal yoke
normal yoke
summer stump
normal yoke
#

this is all i see when I press it

summer stump
#

Hmmmm alright

#

What is the package SUPPOSED to have?

#

It seems to have a model with its associated texture(s) and material(s)

#

Is there supposed to be more?

normal yoke
#

oh...

#

shit...

#

I just realized I only downloaded the hair of the character...

#

I appreciate your time

#

I will grovel in my stupidity now

topaz mortar
#

pretty much what we do most of the time

normal yoke
#

That certainly helps my mood rn I spent way too much time trying to figure this out before coming here..

topaz mortar
#

won't be the last time 😉

#

What is the proper syntax for this? Item is a Script
if (_head.GetComponentInChildren<Item>().GetType() != Item)

#

Or can I just check if it's not null since it should always be of type Item anyway?

strong wren
#

You don't need to get the type if you are just trying to figure out whether the 2 item instances are the same instance

#

What is the goal here?

#

Attaching IDs to Item and comparing those can be used to differentiate between different items that are represented by the same Item type.

normal yoke
#

okay im making another attempt at opening at different model package (its actually the model) and it still wont come up

topaz mortar
#

seems like you should do some basic unity tutorials first, so you actually know what's going on?

#

there should be some in the pinned messages

topaz mortar
normal yoke
normal yoke
cosmic dagger
topaz mortar
#

Why are there green + icons on my item prefabs but not on my itemslot prefabs?
I don't see any overrides

rich adder
topaz mortar
#

I just dragged the prefab into my hierarchy though, so how can there be something new?

#

is it because it has a different parent?

rich adder
topaz mortar
#

hmm kaj

hybrid karma
#

how do i set fullScreenMode? i literally can not find info anywhere, only for fullScreen

sinful heath
#

im new and i just want to learn how to code, is learning on youtube or docs better

rich adder
summer stump
sinful heath
#

Ok, thx guys 👍

topaz mortar
#

tutorials are great for getting familiar with unity and learning what's possible
but they're terrible for actually getting better at building your own games

hybrid karma
#

why might i get an out of range exception when i call any index in an array?

slender nymph
#

the array is smaller than the index you are providing

hybrid karma
#

it has 2 values, i call 0 and 1

slender nymph
#

show the code

hybrid karma
#
public void SetWindowMode(int mod)
    {
        if (mod == 0) Screen.SetResolution(res[0], res[1], FullScreenMode.ExclusiveFullScreen);
        if (mod == 1) Screen.SetResolution(res[0], res[1], FullScreenMode.Windowed);
        else Screen.SetResolution(res[0], res[1], FullScreenMode.FullScreenWindow);

        mode = mod;
        PlayerPrefs.SetInt("WindowMode", mod);
    }
    public void SetResolution(int reso)
    {
        if (reso == 0) res = new int[2] { 848, 480 };
        if (reso == 0) res = new int[2] { 1280, 720 };
        if (reso == 0) res = new int[2] { 1920, 1080 };
        if (reso == 0) res = new int[2] { 2650, 1440 };
        else res = new int[2] { 3840, 2160 };

        resolution = reso;
        PlayerPrefs.SetInt("Resolution", reso);

        SetWindowMode(mode);
    }```
#

god damnit

#

nevermind

#

i called setwindowmode before set resolution

slender nymph
#

yeah that'll do it. also what's up with the 4 identical conditions? you do know if that condition is true only the last one will matter. and you're allocating 4 arrays for it but then only using the last one

hybrid karma
#

i realised that also

hybrid karma
#

now im getting an out of range error with a dropdown menu when i try set its value to 4, it has 5 options so i dont get it

hybrid karma
#
volume = PlayerPrefs.GetFloat("Volume");
        mode = PlayerPrefs.GetInt("WindowMode");
        resolution = PlayerPrefs.GetInt("Resolution");
        Debug.Log("v " + volume);
        Debug.Log("m " + mode);
        Debug.Log("r " + resolution);
        modDD.GetComponent<TMP_Dropdown>().value = mode;
        resDD.GetComponent<TMP_Dropdown>().value = resolution;
        volS.GetComponent<Slider>().value = volume;```
i can see in the log that resolution is set to 4, the dropdown object has 5 options
topaz mortar
#

which line is throwing the error?

hybrid karma
#

a line in the TMP_Dropdown script

gaunt ice
#

you have two TMP_Dropdown here

hybrid karma
#

yeah

#

i get the error for the resolution dropdown but not the mode dropdown

#

if i remove the = mode from the script then the resolution one works...

#

what

topaz mortar
#

are you sure you're setting the correct dropdown component?

hybrid karma
#

yeah

gaunt ice
#

can you drag and drop the reference of tmp dropdown to your script component? it is safer, an log the length of options of tmp dropdown

hybrid karma
#

yeah when i log the options count it says 5

#

wtf i just swapped the order so it sets resolution then mode and now it all works??

#

is this a unity/tmp bug?

slender nymph
#

most likely what happened was after the first change you made you saved the code and whatever was initially causing it had already been fixed and was finally compiled

#

unless you are doing something in one of the OnValueChanged events that is causing the issue

hybrid karma
#

i just changed the order back and it broke again

slender nymph
#

then it's probably something you are doing in OnValueChanged

#

of course you haven't even provided the stack trace, or even the actual error message for that matter. so it's hard to tell

young hawk
#

The only two reasons it could happen are some code running on the value being changed as box said, or a very reliable and specific race condition. The latter is incredibly unlikely (honestly probably impossible), so it's probably the former.

hybrid karma
#

i see, it was the same index out of range error as i was having before but when i clicked the error message it took me to a line of code in the TMP_Dropdown script

slender nymph
#

show the stack trace

shy cloud
#

I just set up a slider in my project, but when I try to interact with it, I always just interact with the object behind the slider. I have already searched the internet for solutions, but nothing I found there worked.

slender nymph
hybrid karma
#

is this stack trace

slender nymph
#

and what is line 46 of SettingsMenu.cs

shy cloud
hybrid karma
#

that is where i set the resolution, its the same error i had before

slender nymph
#

and let me guess, that method is being called in OnValueChanged, yes?

hybrid karma
#

indeed

slender nymph
#

can you share the entire script in a bin site so we can get an actual understanding of what exactly is happening in this code

hybrid karma
#

why? i already solved it

young hawk
#

You did not

#

You need to know why it happened to solve it, otherwise you're just masking the issue

slender nymph
#

that's a bandaid fix at best and does not actually solve the underlying issue

young hawk
#

^

hybrid karma
#

that was when i figured it out, its because when i set the value it called something that isnt supposed to be called first

young hawk
#

What object was being indexed

hybrid karma
#

an int array for resolution

slender nymph
#

do you want to actually solve this? or would you rather go with your bandaid fix and have to make sure that you always do things in a very specific order and potentially run into this issue many times in the future?

young hawk
#

So modDD.TMP_DropDown.OnValueChanged indexed an array for resolution?

#

That's a little odd

#

Does it index it using the value in the resolution dropdown

hybrid karma
#

the resolution dropdown creates an array with the resolution height and width and then mode uses it to set the actual resolution and window mode, if i call mode first there is no array yet

#

i didnt realise setting the value in script called onvaluechanged

young hawk
#

Why does the dropdown create an array?

#

How are the array values tied to the currently select value of the dropdown?

slender nymph
slender nymph
hybrid karma
#

you mean like why did i personally do it this way?

slender nymph
#

yes. you're also hardcoding these values for some reason instead of getting the available options that the device supports

hybrid karma
#

idk breh it was was the first thing i thought of

slender nymph
#

well if you were to get the available options using unity's API then you could create the relevant arrays and cache them before either of these methods are called. although you don't even need arrays, just use a Vector2Int or even just two ints since you're just storing 2 ints and using them individually instead of using the array for anything

timber sundial
#

Hello just a quick question about this error im getting. Im trying to do

#
        Debug.Log(tileManager.GetInstance().columns + "   " + tileManager.GetInstance().rows);
        Debug.Log(newUpdate[0, 0].currentState);
#

but its telling me that the debug.log for newUpdate[0,0] object reference is not set to an instance of an object?

slender nymph
#

that means you have created the array but not actually assigned anything to that position in the array

#

the default value for reference types is null

gaunt ice
#

you just create the array of reference but no any instnace is referenced

timber sundial
#

oh... so just foreach loop through and give it a tile?

slender nymph
#

not a foreach since that wouldn't work. but for loops, yes

timber sundial
#

ah ok thanks ;-;

storm sand
#

Hey guys I was wondering if I could get some help on my 2D jump.
So my jump is currently FPS dependent, I tried countless ways to fix it but I just couldn't, can you guys help me?

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.

storm sand
#

oh

#

sorry

slender nymph
#

you're calling HandleJumping in Update and adding continuous force to the rb

storm sand
slender nymph
#

yes, you're adding force every frame for that duration

#

this is why your jump is framerate dependent. you would want to do that inside of FixedUpdate not Update

#

but you also cannot use GetKeyDown and GetKeyUp in FixedUpdate because those are only true for a single frame. so you need to split it up to get the input in Update and apply the force in FixedUpdate

storm sand
#

oh, ok I'll try it give me a sec tysm!

silver flicker
#

Yo can anyone help me out here? I got these 2 balls - you can pick which one u want to use (coop type thing) And for some reason it doesn't let me ground check. atm IsGrounded() is constantly true whether you're above the range or not - IsGrounded() method at bottom https://gdl.space/gesefuguva.cs

storm sand
slender nymph
#

oh another possibility is you've selected the wrong transform for the groundCheck object or it isn't actually attached to the player

silver flicker
#

and after disabling all 'jumpable' layers from all objects, I can still infintely jump for some reason

#

The groundcheck objects are correct in the inspector

slender nymph
#

what layer(s) are the player's collider(s) on?

silver flicker
#

as in the player object? or the collider of the player

slender nymph
#

any object attached to the player that has a collider

silver flicker
#

bc currently the objects are on no layers at all and I can still jump

slender nymph
#

including the player object itself

silver flicker
#

all are on default

#

all of them including the player

#

I dont think its a layer issue

#
  • Still infinitely jump
#

That is the player 2 ball

#

Is it an issue with the overlapbox? It was working correctly before I changed it from an overlap circle to a box

slender nymph
#

change your IsGrounded method to this and show what it prints:

public bool IsGrounded()
{
    var hit = Physics2D.OverlapBox(groundCheck.position, groundSquare, LayerMask.GetMask("Jump", otherPlayer));
    Debug.Log($"{hit.name} was detected by the OverlapBox. It is on layer {LayerMask.LayerToName(hit.gameObject.layer)}");
    return hit;
}
silver flicker
#

But I can't see reason to not allow it to be a box

#

ok

#

Upon using the player 1, ground and player 1 was detected

slender nymph
#

huh?

#

can you just show what it actually prints

silver flicker
#

(The true statement is a debug.log saying its grounded

slender nymph
#

oh whoops i forgot to add a check to make sure it doesn't try to print when nothing was hit

silver flicker
#

Upon switching with characters, and jumping, it says the player I jumped with was detected

#

Oh ok

slender nymph
#

looks like your player and ground are on the same layer

silver flicker
#

Oh yeah, Ill change that real quick

slender nymph
#

yeah it's kind of the whole issue. if the player is on the layer you are checking for ground and then its collider will be considered ground for your OverlapBox

silver flicker
#

I see

#

I imagined that the 'other player' string where I input the layer string of the other player would fix that tho right?

slender nymph
#

if the player is on any of the layers that are included in the layermask then it can be detected by the overlapbox

silver flicker
#

I also unset the jump layer in the inspector

#

So there was no layers active for the code to read

#

and it still jumped infinitely

slender nymph
#

and is the log still printing that it has found something?

silver flicker
#

Yeah

#

"Ground was detected by the OverlapBox. It is on layer Default"

#

Oh wait a minute

slender nymph
#
public bool IsGrounded()
{
    var layerMask = LayerMask.GetMask("Jump", otherPlayer);
    var hit = Physics2D.OverlapBox(groundCheck.position, groundSquare, layerMask);
    if(hit)
        Debug.Log($"{hit.name} was detected by the OverlapBox that originated at {groundCheck.position} with size {groundSquare}. It is on layer {hit.gameObject.layer} ({LayerMask.LayerToName(hit.gameObject.layer)}) at position {hit.transform.position}. Other layer to check: {otherPlayer}. {layerMask} ({GetInstanceID()}).");
    else Debug.Log($"No ground detected this frame ({GetInstanceID()})");
    return hit;
}

try that and show what it prints

silver flicker
#

no definition for hit.gameObject.Layer it says

#

think i got it

#

lowercase l on layer yeah?

slender nymph
#

whoops hit shift on that my bad

silver flicker
#

np

slender nymph
#

i made one more change to the log can you copy/paste it again and show what it prints now?

silver flicker
#

sure

fair steeple
#

Hey, can I delete one of these? They are causing multiple ambiguous reference errors.

slender nymph
#

delete the second as you are probably not using UIElements. you would know if you were

silver flicker
fair steeple
#

Yeah, VSCode added it on it's own

slender nymph
#

oh wait, you're also calling IsGrounded like 5 or 6 times per frame. you should start by caching the result of that at the beginning of Update instead of calling it that many times per frame. it will not only save a bit of performance, but your logs won't be littered with so many of those calls. because right now you're screenshotting fewer logs than you are printing each frame

silver flicker
#

Alr

slender nymph
#

after you make that change you should post your updated code so i can take another look at it

silver flicker
#

ok I'll be back later bc i gotta head out for now

#

Ill try that when im back in

#

thanks tho man

ashen anchor
#

Hey guys! I need some help with my code. Im trying to do a Tower Defense Game. Ive build a Wave System but it doesnt work that quite like i wanted too. The WaveTimer gets at the start once with 9.98 Debug.Loged. So the WaveTimer doesnt work. Maybe someone can help me.

https://gdl.space/omegazepib.cs

timber tide
#

Where are you delcaring WaveTimer or am I blind ignore this just woke up ;)

turbid robin
#

the tutorial that i am following is using the "Istantiate", but when i try to use it i get an error, why?

ruby python
#

Spelling

turbid robin
ruby python
#

Look at the red line

turbid robin
#

oh i am stupid

#

sorry and thx for the help

fossil drum
timber tide
#

and because you send it into the function, it's a value type and not a reference type (basically it creates a duplicate of the value and passes it into the function)

#

so updating it and sending it back in won't change

turbid robin
ashen anchor
timber tide
#

That would be the easiest idea here, and you can reuse it.

fossil drum
languid spire
#

Wave1 and Wave2 are only called once so there is no timing function going on there

timber tide
#

Could also make a single wave function as well.

#

and just give it different parameters, but yeah it's only being called once

turbid robin
ashen anchor
fair steeple
#

Hey, is Vector3.forward relative to the object's rotation?

languid spire
#

yes, only once

ashen anchor
#

Why? WaveCounter is one and stays at one for the moment

#

Ahhh because of !IsWaveActive

languid spire
#

exactly

ashen anchor
#

Okay. What exactly can i do about it? Im not advanced sry

languid spire
#

make Wave1 and Wave2 Coroutines and loop within them

timber tide
#

Could kinda just remove that check completely since you are also checking the wave number

ashen anchor
languid spire
ashen anchor
languid spire
#

you've made coroutines before so you should know how they need to work

ashen anchor
#

Yeah! I need to to WaitForSeconds. But why do i even need a Coroutine here?

languid spire
#

you dont need waitforseconds and you need a coroutine because you want it to loop but not block

echo dove
ashen anchor
languid spire
#

that is why Unity wrote documentation so you can reference it

echo dove
# echo dove Nope it isn't

This is another acc because my main got disabled ..... Probably because I was joking around I was underage in another server

echo dove
#

Anyways it would be great if you would reply

fair steeple
#

How do you give something like AddForce to a Character Controller? Move just teleports around.

ruby python
#

You need a rigidbody, google, there are looooads of tutorials etc.

fair steeple
#

I though it wasn't compatible with CC

ruby python
#

Oh, the character controller component is already a rigidbody of sorts. Have a look for chracter controller tutorials.

fair steeple
#

Thanks, I'll have a look tomorrow, it seems a bit complicated to do

ruby python
#

It's really not.

fair steeple
#

Maybe but everything is complicated when you need to sleep lol

ashen anchor
ruby python
languid spire
#

inside your while loop

fair steeple
#

Oh neat, there's some stuff that I will need later too

#

Well cya and thanks for the help, I really need to sleep

ashen anchor
dry tendon
#

is there any way to see the console in android? To see logs and that kind of things

languid spire
ashen anchor
languid spire
#

Look at your code and think about it

ashen anchor
languid spire
ashen anchor
languid spire
#

right so why are you testing WaveCounter again. Not once but twice?

ashen anchor
languid spire
#

but it can only be 1 because that is the condition for starting it in the first place

ashen anchor
languid spire
#

irrelevant

ashen anchor
# languid spire irrelevant

Ahhhhh
The while can only be activated if WaveTimer is above zero. So in that case there cannot be an if WaveTimer is under zero

languid spire
#

yep, the else code should be after the while is complete

ashen anchor
#

Okay that works. It changes to two. But the Balloons still dont get spawned

languid spire
#

think about it, under which conditions do you Spawn balloons and when is that condition set?

ashen anchor
#

if WaveCounter == 1. That doest make sense because the Coroutine only gets started when its 1. So i deleted that. Now the Balloon Coroutine gets started when the Wave Coroutine starts

languid spire
#

yes, but the condition within the spawner is not being met because you are setting it at the wrong time

ashen anchor
#

So IsWaveActive needs to be true before the BalloonCoroutine starts

languid spire
#

yes

#

it only needs to be set once so has no place within the while

ashen anchor
#

Thats true. Im trying out wait

#

It is working but there is still one last problem. After Wave1 The Balloon and the TestBalloon get spawned. I dont want that. I only want that TestBaloon gets spawned

languid spire
#

now why do you think that is?

ashen anchor
#

Because the Coroutine of Wave1 is still loading.

#

or on

languid spire
#

exactly, so when you Start the SpawnBallons coroutine save the return value and use a StopCoroutine with it at the end of Wave

topaz mortar
#

I have a button that is calling a script on my Menu object
Can I somehow pass a component of the button to the Menu script?

timber tide
#

Button events allow you to pass a single parameter, no? I forget

ashen anchor
languid spire
#

because you need it for StopCoroutine

topaz mortar
ashen anchor
timber tide
#

You can also pass in a delegate if you need to if you can't pass the type/ref value. Make like a delegate getter

languid spire
#

not waitforseconds. The return value from StartCoroutine

ashen anchor
#

So Balloon and WaitForSeconds?

languid spire
#

no. Do you not understand what return value means?

ashen anchor
languid spire
#

when you call a method and StartCoroutine is a method is can return a value.
In this case StartCoroutine returns a value of type Coroutine

#
int MyMethod() { return 1; }

returns a value of type int containing the value 1

ashen anchor
#

So we return a IEnumerator

languid spire
#

no

#

a Coroutine

#

again look at the docs

ashen anchor
# languid spire

Iam so dumb. I was the wole time on a wrong documentation. We can stop the coroutine by yield return null;

languid spire
#

no

#

in your case you need to stop it explicitly using StopCoroutine

ashen anchor
#

StopCoroutine(SpawnBalloons()); That doesnt work

#

You say I need a return in there

languid spire
#

omg

Coroutine cor = StartCoroutine ...
...
StopCoroutine(cor);
sand glen
#

What am i missing? why is there no UnityEngine.UI documentation?

ashen anchor
languid spire
#

show me the code you now have for Wave1

ashen anchor
#
    {
        WaveTimer = 10;

        int WaitForSec = 3;

        IsWaveActive = true;
        Coroutine cor = StartCoroutine(SpawnBalloons(Balloon, WaitForSec));

        while (WaveTimer > 0)
        {

            WaveTimer -= Time.deltaTime;
            Debug.Log(WaveTimer);

            yield return null;
        }

        IsWaveActive = false;
        WaveCounter += 1;
        StopCoroutine(cor);

    }```
languid spire
#

perfect.
Now one thing for you to think about
The only difference between Wave1 and Wave2 is the GameObject being passed to SpawnBalloons. So why not pass that as a parameter to Wave then you only need 1 Wave Coroutine

ashen anchor
languid spire
#

exactly, you've got it

ashen anchor
#

Thanks

topaz mortar
#

Any idea what could cause this?
It just randomly starting happening when I run my game, doesn't break anything though and I got no idea what caused it

languid spire
fringe lava
#

It's just annoying

#

Does not affect the game

topaz mortar
#

kaj cool thx

#
[SerializeField] private GameObject _shoulders;
[SerializeField] private GameObject _body;```
I want to replace ^ with the array below, but can't seem to find the correct syntax
Is it possible to do this? I need to assign all the gameobjects in the editor
`[SerializeField] private GameObject[] itemSlots = {"head", shoulders };`
#

ah nvm
[SerializeField] private GameObject[] itemSlots;
and then I can just assign as many fields as I need

timber tide
#

ye, it will extend the array like a list in the editor if needed

ruby python
#

Hi all,

Would anyone please take a look at the vid and code and tell me what I'm missing please, been trying to figure this out for about an hour. lol.

Basically I'm trying to write a really simple script so that the suspension rotates to meet the wheel.

Wheels are controlled with NWH's wheel controller asset, now the annoying thing is that the angle of the suspension arm is matching the 'calculated' angle (from the suspension arms origin), but it doesn't seem to be correct and I'm completely baffled.

Video
https://streamable.com/qx2u5h

Script
https://pastebin.com/eAeiE47y

turbid robin
#

hi, i am following a tutorial to learn unity ( https://youtu.be/XtQMytORBmM?si=N0uFeL49lJdUppGs ), i am making flappy bird with unity, the tutorial did something that i didnt understand very well, can someone pls explain?
this is the part:

Instantiate(pipe, new Vector3(transform.position.x, Random.Range(Lowest,Highest), 0), transform.rotation);```
in the tutorial he use this part to spawn the pipes, but i didnt undertand how to use it (i just copied)

GMTK is powered by Patreon - https://www.patreon.com/GameMakersToolkit

Unity is an amazingly powerful game engine - but it can be hard to learn. Especially if you find tutorials hard to follow and prefer to learn by doing. If that sounds like you then this tutorial will get you acquainted with the basics - and then give you some goals to learn ...

▶ Play video
polar acorn
#

What do you not understand about that? Which function do you not know?

turbid robin
#

the founction instantiate

#

and also the part with "new vector3"

stray cosmos
#

Instantiate creates an instance of the game object you put in

#

new just indicates that you're introducing a brand new Vector3 which is being defined then and there

turbid robin
stray cosmos
#

Do you mean that your game is 2D?

turbid robin
#

yeah

#

flappy bird

gaunt ice
#

2d is just 3d but you dont care one axis

#

in most case the z axis will be ignored

stray cosmos
#

Unity is p much built around 3D so a lot of the functions expect 3D Vectors, but usually you can put something like 0 or 1 for the z value

turbid robin
#

oh ok

#

so i am creating a new vector and the moving only the y position right?

#

because the first one is with the trasform.posizition, and z is 0

stray cosmos
#

That particular Vector3 is deciding where you want to place the object you're going to instantiate

turbid robin
#

ok now i am understanding

#

thx for the help

stray cosmos
#

👌

prisma blaze
#

I want to test OnGameOver function that has 11 references, specifically the IsGameOver bool and the reason var, how can i test for that while disregarding stuff like SpawnUIScreen and gameobjects? do i have to comment it out or something? should i find a way to separate it?

frigid nimbus
stray cosmos
#

Ok TIL

turbid robin
#
float Lowest = transform.position.y - Altezza;
float Highest = transform.position.y + Altezza;```
also the tutorial made me create this using the variable `Altezza` that has a value of 10.
after i used lowest and highest in:
```csharp
Instantiate(pipe, new Vector3(transform.position.x, Random.Range(Lowest,Highest), 0), transform.rotation);```
why i did this and i used the variable `Altezza` and not just a value for lowest and higest?
prisma blaze
#

what if i want to use Nunit? like i want to still test for them if more code/logic is added

west peak
prisma blaze
#

yeah

west peak
prisma blaze
#

apparently their test framework is a version of nunit

west peak
#

so is perfect ^^

prisma blaze
#

huh, why would you test in edit mode and not play mode?

turbid robin
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MidleScript : MonoBehaviour
{
    public LogicScript logic;
    // Start is called before the first frame update
    void Start()
    {
        logic = GameObject.FindGameObjectsWithTag("Logic").GetComponent<LogicScript>();
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    private void OnTriggerEnter2D(Collider2D collision)
    {
        logic.ScoreUpdate();
    }
}```
i get an error on `.GetComponent<LogicScript>();`
west peak
frigid nimbus
prisma blaze
west peak
#

here you have inventory test in edit mode, i don't need to load scene, and in playmode you load the scene and verif like NPC path

turbid robin
prisma blaze
#

ah so play mode is for something integration or system testing

flat slate
#

I need help

frigid nimbus
prisma blaze
turbid robin
#

thx, i used "tab" without looking

polar acorn
flat slate
#

In my game I created a transition in the start menu but it always plays behind the buttons and not in front of them. What do I have to do?

frigid nimbus
# turbid robin what do you mean sorry?

for the y value on your script when instantiating a pipe, you are choosing a random value between the value of the variable Lowest & Highest, the Lowest var is the transform.position.y of the object that has the script attached - Altezza and Highest is the same but + Altezza, so you get a range of values in wich the pipe could be instantiated, you use your variable to create that "space" or "offset" or whatever you want to call it, and use a variable so you can quickly adjust it and make the code more readable

frigid nimbus
oak mist
#

yo, im very new to unity and trying to get a very simply stationary turret working

#

when the i use the arrow keys, the turret is supposed to rotate left and right whilst remaining stationary

#

but im getting this:

#

the turret moves from the base

#

heres my script

#

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

public class Rotation : MonoBehaviour
{
    public float rotationSpeed = 50.0f;

    void Update()
    {
        float horizontalInput = Input.GetAxis("Horizontal");
         transform.Rotate(Vector3.up * horizontalInput * rotationSpeed * Time.deltaTime, Space.Self);
    }
}

frigid nimbus
# flat slate

In you UI order the bottons are on the top of the animation, try changing the canvas sort order in the inspector

oak mist
#

and my hierachy:

#

the script is inside my base parent file (the drop down one)

#

i tried switching it and doesnt change anything

#

any help would be great

frigid nimbus
flat slate
#

no

frigid nimbus
#

Its a image?

flat slate
#

wait

#

no its a canvas

#

you are right

frigid nimbus
#

try changing the sort order

flat slate
#

okay

#

thanks

#

it worked

#

thank you

frigid nimbus
#

🤟🏻

frigid nimbus
oak mist
#

it was in the gun section, which was inside the base parent

#

ive fixed it its ok now

#

thank you

#

i had my parenting a little weirf

#

weird that was all#

gray arrow
#

hi guys, I need a simple answer for this one:

I want to use trig funtions, but I need an angle in either degrees or radians to do so.
how do I convert a 2D sprite's rotation quaternion into an angle float?

its probably a one-line-of-code thing, but im too bad at coding to do it lmao

frigid nimbus
#
// 1. Get the sprite's rotation Quaternion 
Quaternion spriteRotation = spriteTransform.rotation;

// 2. Convert the Quaternion to Euler angles
Vector3 spriteEulerAngles = spriteRotation.eulerAngles;

// 3. Extract the angle you need (in degrees)
float rotationAngleDegrees = spriteEulerAngles.z;

// If you want the angle in radians, you can convert from degrees to radians
float rotationAngleRadians = rotationAngleDegrees * Mathf.Deg2Rad;
gray arrow
#

cheers man 👍🏻

frigid nimbus
#

🤟🏻

#

Should do the trick

magic stream
#

I've been trying to fix my collisions for 2 hours now and I have no idea why it doesn't work. Can someone help me please ? On the first picture there are properties for objects and on the second one for the player.

cosmic dagger
hushed saffron
#

hey I'm new to unity what are my opportunities to get the world map into the editor?

#

I want to build a strategy game

young warren
tender stag
#

does the interface look correctly?

#

so then i can do something likecs (inputItem as IDurable).Durability = (inputItem as IDurable).MaxDurability;

#

can i make this any simpler?

#

or is it alright

young warren
queen adder
#

Uh i have a MonoBehaviour that has an public UnityEvent MethodName; and a method called MethodName in that MonoBehaviour:

public class Class : MonoBehaviour
{
  public UnityEvent MethodName;

  // Error: Class already contains a method named "MethodName"
  public void MethodName()
  {
    
  }
}

How could i accept both of them?

young warren
queen adder
#

Any other solutions?

young warren
#

There's no reason for your variable to be the same as your method name

#

Wait, does it really not allow that?