#💻┃code-beginner

1 messages · Page 78 of 1

slender sinew
#

The size in aseprite will depend on the PPU (pixels per unit) you choose

sweet zenith
#

If you're trying to launch something just set its velocity.

#

Like targetRb.velocity = launchDirection.normalized * launchSpeed

uncut holly
#

hello i ran this code but it gave me and error

summer stump
eternal falconBOT
summer stump
#

Oh, did you SAVE the script? Maybe that is the issue? The yellow on the left means unsaved. Dunno if that affects the build, but it certainly would affect unity compilation

uncut holly
gaunt ice
#

build failed
see the log

#

again, this is not unity issue

timber tide
#

I'm guessing that the top level statement (program wrap and entry point) are already applied. Try removing it and just print to console.

inner marsh
#

so im trying to get boats to float via the HDRP water system, this is my code and it works, but is there a way to expand it so i can have the boat not just move straight up and down but move via points so like the front would be higher than the back? ```using UnityEngine;
using UnityEngine.Rendering.HighDefinition;

public class Fit : MonoBehaviour
{
public WaterSurface targetSurface = null;

// Internal search params
WaterSearchParameters searchParameters = new WaterSearchParameters();
WaterSearchResult searchResult = new WaterSearchResult();
void Update()
{
    if (targetSurface != null)
    {
        // Build the search parameters
        searchParameters.startPosition = searchResult.candidateLocation;
        searchParameters.targetPosition = gameObject.transform.position;
        searchParameters.error = 0.2f;
        searchParameters.maxIterations = 8;

        // Do the search
        if (targetSurface.FindWaterSurfaceHeight(searchParameters, out searchResult))
        {
            gameObject.transform.position = new Vector3(gameObject.transform.position.x, searchResult.height, gameObject.transform.position.z);
        }
        else Debug.LogError("Can't Find Height");
    }
}

}

summer stump
timber tide
#

ah, yeah probably don't want to start with one of those

#

usually I go with the console/windows app template

#

otherwise blank

noble urchin
#

Anyone know why my Node isnt on the Player or enemy?

slender nymph
#

you might wanna check #854851968446365696 for what to include when asking for help. and also maybe realize that we don't have context for what is supposed to be happening or what this screenshot is supposed to convey as the issue

gaunt ice
#

no one know
looks like the mapping from world space to grid is wrong

nimble apex
#

bruh i gonna go with TGA

timber tide
#

psd photoshop doc?

nimble apex
#

yes

willow scroll
nimble apex
#

sad

willow scroll
#

Does anybody know why my background is serialized so wrong in my custom editor?

public bool useBackground = true;
[HideInInspector] public ComponentColorSwitch<Graphic> background;

Custom editor class: https://gdl.space/fatodezane.cs

molten wigeon
#

Guys could anyone recommend me Unity C# book - like for dummies type.
What I need is something that I can just reference "What is method" , "How to make For loop" .... basically explaining every important concept. SO its easily referencable for my absentminded self 😂
Could be free PDF or payed PDF...or even website if there is such

willow scroll
molten wigeon
# willow scroll Do you want to learn C# from the start?

Well yes. I am artist that want to make games. I allready started on tutorials and such. And I am making good progress. But everytime I let say dont do something, and I start again I have to go back to youtube vid to look it up. And its vaste of time.
Having a book open would be better

#

So I am not like 0% begginer. Let say 10%

hasty wind
#

Tbh am the same am in lvl 1 IT in college and i have just been researching how to develop my own app/ game but youtube vids are soo annoying

willow scroll
molten wigeon
willow scroll
willow scroll
hasty wind
#

Whats the best app or tutorial to start designing games for a beginner?

cosmic dagger
#

how did you get good at becoming an artist? i bet it's similar; practice . . .

eternal needle
# molten wigeon Guys could anyone recommend me Unity C# book - like for dummies type. What I nee...

First do c# then unity, trying to learn both is going to be way harder. If you're unsure of what to code, I say do challenges online which give you some guide of what problems exist and what you can solve. Problems range from printing out "Hello world" to solving complex data questions, on sites like leetcode or whatever you choose to use.
I used to tutor in coding, and regardless of how long someone's been coding its quite clear when they havent done thought provoking challenges. It provides very good knowledge on how to debug when something is wrong

molten wigeon
#

Its not that... I just need a reference for syntaxes and stuff. Also and especially for things you dont use all the time.
I dont need guide on how to code. Just reference

timber tide
#

Do some easy stuff then do some code reviewin

molten wigeon
#

I have been coding CSS forever now. And I still all the time go to CSS school site to check syntaxes

eternal needle
molten wigeon
strong wren
#

I think the process of learning both is very comparable, which is looking up things as you go

timber tide
#

implying I know the syntax. My ide just does it for me

molten wigeon
#

That is point also 😄

eternal needle
#

itll be quicker than trying to find the same answer in a wall of text in a textbook for example, where you cant quickly search keywords since words like method void etc will appear hundreds of times

molten wigeon
#

Its waste of time

timber tide
#

chatgpt is fine honestly

strong wren
timber tide
#

especially for starting on new languages it's pretty good at giving you advice on basic stuff

eternal needle
#

With the examples you listed, ( "What is method" , "How to make For loop"), these would definitely bring up the microsoft docs or some other good website. If you're talking about how to do stuff in unity, then yea unfortunately most guides are just long videos. A lot of them are from people who dont really know what they're doing either

#

I use video guides more as an indicator to what exists, like stuff in the unity api i didnt know

molten wigeon
timber tide
#

obviously it's better to read the documentation, but sometimes you can miss little tidbits which it'll clear up for you usually

molten wigeon
#

Its amazing how good is Chat GPT for learning code, I must admit

#

Anyway. Thanks guys 🙏

timber tide
#

ye

modest barn
#

How do I read a .txt file? I'm developing an Android app and I've given to understand that the process is different than normal C#. Please ping me if you reply - TIA!

languid spire
modest barn
#

A script

languid spire
#

which path

modest barn
#

I have a large list of 10000 words and storing it in memory seems to crash the Editor.

#

So I will store it in a text file and read from there, line-by-line, hopefully so that the entire thing isn't stored in memory at one time.

#

But I'm new to C#, so no idea how to deal with files, let alone read line-by-line.

modest barn
#

I suppose that means it'd be in Assets? Doesn't matter for the purposes of the app.

languid spire
#

you have 2 choices.

  1. Store the file in a Assets/Resources folder and use Resources.Load to read it
  2. Store the file in Assets/StreamingAssets and use UnityWebRequest to read it using Application.streamingAssetsPath
modest barn
#

What's the difference between them? What's easier? Which one would better facilitate my line-by-line strategy? Thanks for replying 🙂

languid spire
#

May I suggest you go and read the Unity docs on both of them

modest barn
languid spire
#

In your case very little difference. Option 1 will be easier to code

modest barn
#

Great, thank you. I'm going to have to figure out how to read it line-by-line as all the examples here load the entire file at once...

#

It'll be a fun challenge though - thanks for all your help!

languid spire
#

if you really want to use the standard System.IO.File methods, which includes a ReadLine, you can copy either of the data produced by the above options and write it to Application.persistentDataPath then read it from there

modest barn
#

Great, I'm off to read those docs. Thank you so much!

gaunt ice
modern rune
#

Hey guys can you help me animate emission property of unity material. I want it on and off randomly

Message #💻┃unity-talk

covert nest
#

I have made this class for nodes:

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

public class NodeScript : MonoBehaviour
{
    [SerializeField] private int TravelCost = 99999;
    public int getTravelCost() { return TravelCost; }
    public void setTravelCost(int inCost) { TravelCost = inCost; }

    [SerializeField] private int[] indexCoord = new int[2];
    public int[] getIndexCoord() { return indexCoord; }
    public void setIndexCoord(int[] index) { indexCoord = index;
        Debug.Log($"I am {gameObject.name} and INDEXCOORD WAS JUST CHANGED TO {index[0]} , {index[1]}");
    }

    private bool containsEntity = false;
    public void enterNode() { containsEntity = true; }
    public bool hasEntity() { return containsEntity; }
    public void setContents(bool inContents) { containsEntity = inContents; }

    private GameObject entityContained;
    public void setEntityContained(GameObject inEntityContained) { entityContained = inEntityContained; }
    public GameObject getEntityContained() { return entityContained; }

    // Start is called before the first frame update
    void Start()
    {
    }

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

As you can see, indexCoord is PRIVATE and logs a message every time it is changed.

However, at some point in my game, whenever a certain task is done, which I can elaborate on further if necessary but would take too long to explain here, one node's indexCoord changes. Only one. I normally would be able to figure this out, but the node doesn't log any message when it changes this time, which should be impossible because it is private. I know that the debug log works because when the node's index is initially set, it DOES output that message.

help how does something change it if its private 😨

#

sorry about messy code, im generally new and in a rush

ruby python
#

!code

eternal falconBOT
ruby python
#

Mornin' all, not really sure what I'm doing wrong here so hoping someone can see my mistake, basically using a coroutine to lower the intensity of a point light (muzzle flash point light). The coroutine triggers fine, but the light doesn't 'fade out' like it should. Any ideas? 😕

IEnumerator MuzzleFlashLight(bool leftLastFired)
    {
        if (leftLastFired == true)
        {
            muzzleFlashLightRight.intensity = maxMuzzleFlashLightIntensity;
            if(muzzleFlashLightRight.intensity > 0f)
            {
                muzzleFlashLightRight.intensity -= muzzleFlashLightFadeRate;
            }
        }
        if (leftLastFired == false)
        {
            muzzleFlashLightLeft.intensity = maxMuzzleFlashLightIntensity;
            if (muzzleFlashLightLeft.intensity > 0f)
            {
                muzzleFlashLightLeft.intensity -= muzzleFlashLightFadeRate;
            }
        }
        yield return null;
    }
#

maxMuzzleFlashLightIntensity is set to 1f.
muzzleFlashLightFadeRate is set to 0.1f.

covert nest
#

rather than yield return null use yield return WaitForSeconds(float timeInSeconds) or some other wait function

#

because atm i think your yield return null doesnt do anything to add a delay between fade intervals

gaunt ice
#

no loop, just sequential statements

timber tide
languid spire
quiet storm
#

hey everyone, im trying add jumping in my game, the problem is that at the end of the jump its like the player hits some sort of ceiling and immediately stops, it is extremely jarring, any clue on how to fix this?

        if(canJump && jumpInput > 0){
            rb.AddForce(transform.up * jumpForce, ForceMode.Impulse);
            canJump = false;
            Debug.Log($"adding force to jump {rb.velocity}");
        }```
covert nest
gaunt ice
#

you should use vecto2int or int2, to save memory and prevent the length of array passed < 2

languid spire
timber tide
#

steve's probably right though but I would assume you'd get some errors in the console

covert nest
#

see this is weird asf because im getting no error messages

#

ill put a pure string debug log before indexCoord = index just to show when it runs and log the index's length and stuff

#

and see if that tells me anything

#

because when the indexCoord is being changed anomalously its not just changing to null or anything

#

its changing to another valid index

#

but not the correct one

timber tide
covert nest
#

nothing at all

#

doesnt run anything in there yet somehow changes the indexCoord

#

i am clueless

#

is there any way AT ALL to change a private attribute from outside the class, without using its setter??

gaunt ice
#

setting breakpoint or remove the function calls to read the error and found out who call it
btw still recommend you use vector2int or int2 instead of array

covert nest
#

if i change from int[] to int2 wont i have to change it everywhere else where setIndexCoord is called when the nodes are initially set

#

and wherever the indexCoord is read

covert nest
#

that way ill be able to see exactly when the change is made

languid spire
covert nest
#

sounds like it might be it

#

because the anomalous change is always like

#

it sets the indexCoord to a coordinate in the same relative positione

#

every time

languid spire
#

if you do not know what reflection is then you are not using it

covert nest
#

unintentionally maybe?

#

im desparate ☠️

languid spire
#

unlikely

covert nest
#

maybe this issue is somehow related to LeanTween

#

i know that the change occurs right after an object tweens to that node

gaunt ice
languid spire
#

Ah, the only way to change the value of indexCoord without actually changing the value is if you are replacing the whole Node instance with a different one

covert nest
#

nodes are never instanced in my build, they are already set in locations

#

and its name doesnt change so im pretty sure its the same one at least

languid spire
#

of course they are instanced. They are Monobehaviours

covert nest
#

my head hurts

#

well yeah but like during runtime they never are

#

as in like

#

by any scripts i made

#

no new ones, at least

#

the instances that exist are the ones already there

languid spire
#

tell you what. why not duplicate your Debug.Log into the get method and prove that

#

also add the gameObject.GetInstanceID to the Debug.Log

covert nest
#

ill try that

languid spire
#

Coz I think you are calling get on a different object than you think you are

covert nest
#

alright, changed it to this

public int[] getIndexCoord() {
        Debug.Log("GETTING INDEXCOORD");
        Debug.Log($"I am {gameObject.GetInstanceID()} and INDEXCOORD is {indexCoord[0]} , {indexCoord[1]}");
        return indexCoord; }```
#

so this is just the get method

#

not supposed to change anything idk

languid spire
#

thats fine

timber tide
#

and you're not changing anything with the getter?

languid spire
#

now make sure you log the gameobject instanceid of the gameobject you are working with

quiet storm
timber tide
#

So are you constantly using a force as you jump instead of once?

quiet storm
#

just once, when i press the space bar

covert nest
#

and to add debug logs in that causes INTENSE lag

#

long freezes

timber tide
#

just use the breakpoints

#

lol

#

more so if you're doing pathfinding even

covert nest
#

it would break around 120^2 times

timber tide
#

Hmm, I guess you can probably log it then write to plain text and instead of the console

covert nest
#

icl if i dont have this solved soon im just gonna have the indexcoord manually fixed every time something tweens to that node

#

because i am very much in a rush

#

this due tomorrow 🥲

topaz mortar
#

Do I need to use async & await for database queries in C#?

languid spire
topaz mortar
#

remote

gaunt ice
#

maybe

languid spire
topaz mortar
#

that is weird 😛

gaunt ice
#

you need to stuck the thread before calling the method that use the data
but you can do other stuffs while waiting the data by async

woven arrow
#

Hello, I need help with the following problem:

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

public class PlayerMovement : MonoBehaviour
{
    private GameObject gameRules;
    public GameObject otherPlayer;

    public float speed;
    public string horizontal;
    public string vertical;
    public bool faenger = true;
    void Start()
    {
        gameRules = GameObject.Find("GameRules");
    }

    // Update is called once per frame
    void Update()
    {
        Vector3 bewegung = new Vector3(Input.GetAxis(horizontal), Input.GetAxis(vertical), 0);
        gameObject.transform.position += bewegung * Time.deltaTime * speed;
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        UnityEngine.Debug.Log("coll");
        if (faenger && collision.gameObject.CompareTag("Player"))
        {
            FaengerSwitch();
            UnityEngine.Debug.Log("Switch!");
        }
    }

    public void FaengerSwitch()
    {
        gameObject.transform.position = new Vector3(5, 0, 0);
        otherPlayer.GetComponent<Transform>().position = new Vector3(-5, 0, 0);
        UnityEngine.Debug.Log(faenger);
        faenger = !faenger;
        UnityEngine.Debug.Log(faenger);
        otherPlayer.GetComponent<PlayerMovement>().faenger = !faenger;
    }
}

I use this script for my two players who have to catch each other. The problem: Changing from faenger = true to faenger = false only works the first time, then faenger no longer changes when catching. I would be really grateful if someone could help, I'm really desperate right now and the internet couldn't help me either!
Thanks in advance!

eternal falconBOT
woven arrow
#

oh, sorry

languid spire
#

I meant use a paste site

woven arrow
#

sorry i'm new here😅

timber tide
#

After FaengerSwitch() what state are both in

gaunt ice
#

Two oncollisionenter are called one after one then the faenger changes from true->set to itself’s and other’s to be false-> call other oncollision enter -> reverse the process

woven arrow
gaunt ice
#

Nothing are changed finally

timber tide
#

ah ok so it's just not changing is the problem

covert nest
#

lets GOO chatgpt finally helped me

timber tide
#

should add a cooldown buffer between tagging

covert nest
#

i changed getIndexCoord() to:

public int[] getIndexCoord() {
        return (int[])indexCoord.Clone(); }```
#

turns out getIndexCoord() was exposing indexCoord and allowing it to be changed

#

so now it returns a clone instead yippeee

#

i did not know that was a thing that could happen

timber tide
#

yeah

woven arrow
gaunt ice
#

Oh i misread it is setting itself’s to be false and the other’s be true, but the result should be the same

timber tide
#

another thing too is for them to retag each other they probably need to move from the previous collision spot

scarlet tiger
gaunt ice
#

Oh wait you block the call, i am wrong

languid spire
#

you probably need to change the initial value of faenger to false on one of the players

woven arrow
#

i did that in the editor

gaunt ice
#

A B
T T
F T< after setting itself and other, first call on A
T F < after setting itself and other, second call on B

languid spire
gaunt ice
#

You propagate the original value to other and reverse the one on itself btw

languid spire
#

depending on the sequence of Collision enter

timber tide
#

I'm not seeing T T or F F, more that until they remove theirselves from colliding it won't fire again.

#

but basically it would reset to the same state every collision

languid spire
#

If you start with
A B
T F
Dont know if collision is called on A or B first
If A then
F T
then
T F
if B then
T F
F T

woven arrow
#

but how can it switch twice?

languid spire
#

because both player are calling collision enter

#

in sequence not at the same time

timber tide
#

Need to add a global cooldown between collisions which both should be checking from

#

better idea would be to set a bool when colliding and unsetting it until they are far apart enough

woven arrow
#

But how can A&B call Switch if only one of them is true?

languid spire
#

this is the sequence of events
Collision
CollisionEnter called on A

#

A changes the values
CollisionEnter called on B
B reads the values just changed by A

woven arrow
#

But after the switch there is no collision anymore because I teleported A&B or am I misunderstanding that?

languid spire
#

the collision still happened

gaunt ice
#

It is called on both objects

#

After one collision happens

woven arrow
#

Ahh, now I understand, thank you!

#

So i have to fix this with a cooldown?

languid spire
#

easy

static bool done=false;
 private void OnCollisionEnter2D(Collision2D collision)
    {
if (!done) {
        UnityEngine.Debug.Log("coll");
        if (faenger && collision.gameObject.CompareTag("Player"))
        {
            FaengerSwitch();
            done=true;
            UnityEngine.Debug.Log("Switch!");
        }
} else done=false;
    }
woven arrow
#

Thanks a lot!

languid spire
#

that way only one players collisionenter will fire for each collision

languid spire
# woven arrow Thanks a lot!

I'm an idiot. Forget all of the above
just remove this
otherPlayer.GetComponent<PlayerMovement>().faenger = !faenger;
from your code and you will be fine

#

also move this
faenger = !faenger;
to the end of CollisionEnter

young pine
#

i added a rigid body to a gameobject but it falls through all the objects i have is there anyway to fix that?

woven arrow
languid spire
#

@woven arrow Even better

    private void OnCollisionEnter2D(Collision2D collision)
    {
        UnityEngine.Debug.Log("coll");
        if (collision.gameObject.CompareTag("Player"))
        {
            FaengerSwitch();
            UnityEngine.Debug.Log("Switch!");
        }
    }

    public void FaengerSwitch()
    {
       if (faenger) transform.position = new Vector3(5, 0, 0);
        else transform.position = new Vector3(-5, 0, 0);
        UnityEngine.Debug.Log(faenger);
        faenger = !faenger;
        UnityEngine.Debug.Log(faenger);
    }
woven arrow
#

I've solved it like this now:

private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.CompareTag("Player"))
    {
        FaengerSwitch();
        UnityEngine.Debug.Log("Switch!");
    }
}

public void FaengerSwitch()
{
    faenger = !faenger;
    if (faenger)
    {
        gameObject.transform.position = new Vector3(5, 0, 0);
    }
    else
    {
        gameObject.transform.position = new Vector3(-5, 0, 0);
    }
}
lament silo
#

anyone?

timber tide
#

Probably want to minimize the area where it could break

#

and give us more of an idea cause you've a lot of functionality on it already

lament silo
#

probably in GetSelectedItem

teal viper
#

What exactly breaks? And what does it mean for the tool to break? Where is it in the code?

eager elm
# lament silo anyone?

The entire foundation of your system is messy to begin with. You're gonna keep getting into trouble for every feature you add. Some things to consider:
Why do you check in Update every frame if an item has been selected? Shouldn't each item slot be a button that then will call a method when clicked?
Why do you need to get the IEquippable and ResourceItem every frame? It would be better to cache those when you create the item. ItemHolder should probably be a script of it's own.
And also don't destroy the item each time you select a different one, instead change out the sprite/model.

languid spire
lament silo
#

the slots in which tools break become unusable and deletes itself when selected

timber tide
lament silo
#

well im trying to make minecraft like toolbar system

#

these 4 slots are broken and when i try to switch to them, item model disappears and so does the item inside slot

hidden sun
#

i have a small problem. I want to instantiate a button prefab. I wrote the script, added the component, added the prefab in component. When i start, the prefab isn't adding to object list.(the button should be added when the scene starts.)

eager elm
#

also, why do you have 'GameObject Button;' instead of 'Button Button;'?

timber tide
hidden sun
lament silo
#

the one i was following didnt include toolbar part

#

im trying to make my own

timber tide
#

Is your inventory working without it

#

because make sure you've got that working first before the hotbar

lament silo
#

yes it does but how would i select items

eager elm
timber tide
lament silo
timber tide
lament silo
#

that's toolbar

timber tide
#

and does your inventory work then

lament silo
#

yes

#

i can drag items from one slot to other if that's what ur asking

timber tide
#

Ok, cool yeah

#

Ok, so since minecraft bar isn't type specific, you can pretty much design it how you did the inventory

#

Make another 'Inventory' of slots that will be your hotbar

lament silo
#

it is already part of inventory

#

my problem is that slot becomes unusable when tool breaks

timber tide
#

If your tool breaks you'd just set what ever was in that slot to null

#
        foreach (Transform item in itemHolder)
        {
            ResourceItem resourceItem = item.GetComponent<ResourceItem>();
            IEquippable tool = item.GetComponent<IEquippable>();
            
            if (selectedItem != null && selectedItem == resourceItem.item)
            {
                if (!itemHolder.GetChild(selectedSlot).Equals(item))
                {
                    item.gameObject.SetActive(false);
                    tool.Unequip();
                }
                
                equippedItem = itemHolder.GetChild(selectedSlot).gameObject;
                equippedItem.SetActive(true);
                tool.Equip(itemHolder);
            }
            else
            {
                item.gameObject.SetActive(false);
                tool.Unequip();
            }
        }```
lament silo
#

i guess it already does that? Destroy(itemInSlot.gameObject);

#

in GetSelectedItem

timber tide
#

Where does the tool break. I see unequip and setactive(false)

lament silo
#
if (durability <= 0 && toolObject.canBreak)
        {
            inventory.GetSelectedItem(true);
        }
weak talon
#

how can I put 2 particle systems on 1 object?
And activate them seperatly at different times

lament silo
#

which makes sense

timber tide
#

Well, I'm going to assume the error is in that method and an error for stacking does sound possible

#

so I'd suggest start throwing debugs into it all because there's a lot going on in the script

eager elm
timber tide
late jolt
ancient shadow
#

Most common cause is using OnCollisionEnter/Stay/Exit instead of OnTriggerEnter/Stay/Exit

late jolt
ancient shadow
#

I couldn't tell you tbh, but if it's only needed to find the distance to the player and nothing else then using something like Vector3.distance between the two positions might work better than using triggers

round trench
#

hi

#

i am new to code

#

and i have a problem

#

how can i solve that

languid spire
#

by the looks of those errors by following some basic C# tutorials

round trench
#

okay

#

thanks

ivory bobcat
#

Make sure to have your ide configured

round trench
desert elm
#

If I have a list, can I assign an individual bool value to every entry?

gaunt ice
#

loop

fresh lintel
weak talon
#

I have a bunch of headers for my unity game

[Header("MovePlayer")]
public float origSpeed = 10;
float moveSpeed;
Vector2 moveInput;

[Header("Dash")]
public float dashSpeed;
public float dashCooldown;
public float dashTime;
bool canDash = true;

[Header("Sword")]
public GameObject rotation;
public GameObject attackRange;
bool canAttack = true;
bool attacking = false;

[Header("FirstAbility")]
bool canUseAbility = true;
public GameObject firstAbilityRange;
float firstAbilityCost = 33;

[Header("SecondAbility")]
public float secondAbilityCost = 33;

[Header("Mana")]
public float mana;
public float maxMana;
public Image manaBar;
public Color lightRed;

but for some reason just the [Header(FirstAbility)] isnt woorking
anyone know how to fix

desert elm
gaunt ice
#

you cant do that

round trench
#

what is wrong with my code ?

#

it says there is an error

fresh lintel
desert elm
#

wait no I said it wrongly-

gaunt ice
#

you cant modify the foreach variable
you need to use for loop to modify the list

foreach(type x in Xs){
  x=other;//prohibited
}
fresh lintel
#

for (int i = 0; i < liist.Count; i++)
{
liist[i]=false or true
}

cosmic dagger
desert elm
cosmic dagger
#

what are you trying to do? what is happening instead?

cosmic dagger
gaunt ice
#

cant understand
you mean there is a bool on the component (your script) that on the enemy or you want to store it somewhere

desert elm
#

Right, sorry wait a minute

desert elm
gaunt ice
#

create a bool list, finish

#

btw check if the count>=enemies.length whatever before you loop through the enemies

desert elm
runic dome
#

Hi ! This error is pissing me of, the project is completely new i just installed some package.

gaunt ice
#
private List<bool> some_name=new();
desert elm
#

oh okay

#

thank you

weak talon
#

why does the first ability header not there in inspector
[Header("MovePlayer")]
public float origSpeed = 10;
float moveSpeed;
Vector2 moveInput;

[Header("Dash")]
public float dashSpeed;
public float dashCooldown;
public float dashTime;
bool canDash = true;

[Header("Sword")]
public GameObject rotation;
public GameObject attackRange;
bool canAttack = true;
bool attacking = false;

[Header("FirstAbility")]
bool canUseAbility = true;
public GameObject firstAbilityRange;
float firstAbilityCost = 33;

[Header("SecondAbility")]
public float secondAbilityCost = 33;

[Header("Mana")]
public float mana;
public float maxMana;
public Image manaBar;
public Color lightRed;
wraith wadi
#

can someone help me?
i want to make enemy shoot bullets in whichever direction player is, i tried few things but results are not the way i want.
if player dodge the bullet or change direction then bullets should keep moving in the same direction until it hit another object or cross boundary.

the most accurate result i got is with MoveTowards function but then bullet keep following player.

gaunt ice
#
[Header("FirstAbility")]
bool canUseAbility = true;//default access modifier is private
public GameObject firstAbilityRange;
float firstAbilityCost = 33;
sonic remnant
#

Hello everyone! I'm experiencing an issue where new text appears on my screen whenever I open and close the crafting system, as well as the inventory system. This is demonstrated in the attached video. The scripts involved in this issue are the Selection Manager script, CraftingSystem, and InventorySystem.

https://gdl.space/ivojuvitiy.cs
https://gdl.space/odamedupab.cs
https://gdl.space/uparemikod.cs

timber tide
#

rather velocity has direction ;p

#

so scratch that

#

so instead it would be speed * direction * deltatime

#

and just append to your position (bullet) every update

desert elm
wraith wadi
timber tide
#

Uh, you can just directly update the position

languid spire
desert elm
#

oh okay-

timber tide
wraith wadi
wraith wadi
timber tide
#

for the above method

timber tide
#

movetowards will always chase the target, but the other method will continue in the direction given

#

so if the aim is off, I'm going to assume something is wrong with the direction so I'd debug your methods

wraith wadi
timber tide
#

well, how do you get a direction?

wraith wadi
timber tide
ivory bobcat
timber tide
timber tide
# wraith wadi Thanks

You can also normalize by using vector3.normalize such that:

Vector3 heading = (target.position - player.position).normalized;```
wraith wadi
#

OKayy

timber tide
#

so now you have a direction, give it a speed, and multiply it by deltatime (in update)

sonic remnant
#

Thanks for helping 🙂

#

i really want to solve this

timber tide
#

Well then you should only have the text enable when you IPointerEnter one of your slots

timber tide
# sonic remnant It has to do something with the code. I want to use this to show when i hover ov...

Unity documentation sucks but check this out if you plan on doing tooltips and/or drag and drop features:
https://onewheelstudio.com/blog/2022/4/15/input-event-handlers-or-adding-juice-the-easy-way

lament silo
#

i almost got everything working, now how would i filter this so it doesnt set 2 objects active, only one?

Item selectedItem = GetSelectedItem(false);
foreach (Transform item in itemHolder)
        {
            ResourceItem resourceItem = item.GetComponent<ResourceItem>();
            IEquippable tool = item.GetComponent<IEquippable>();

            if (selectedItem != null)
            {
                if (selectedItem == resourceItem.item)
                {
                    item.gameObject.SetActive(false);
                }
                
                equippedItem = item.gameObject;
                equippedItem.SetActive(true);
                tool.Equip(itemHolder);
            }
            else
            {
                item.gameObject.SetActive(false);
                tool.Unequip();
            }
        }
gusty gyro
#

Hello! I want to ask what is the good collider for these characters? im currently using the polygon collider 2d

rich adder
#

also not a code question

gusty gyro
#

oh mb what is the right channel to ask it?

lament silo
rich adder
lament silo
#

im holding one but it sets two active

rich adder
#

using transforms 🙄

#

anyway what is the pickaxe spawned from?

#

cause its a clone

lament silo
#

a prefab?

rich adder
#

wha?

lament silo
#
void SpawnNewItem(Item item, InventorySlot slot)
    {
        GameObject newItem = Instantiate(inventoryItemPrefab, slot.transform);
        
        InventoryItem inventoryItem = newItem.GetComponent<InventoryItem>();
        inventoryItem.InitializeItem(item);
        
        GameObject newItemModel = Instantiate(item.model, itemHolder);
        newItemModel.SetActive(false);
    }

here

#

last lines

rich adder
#

ok so ur making it twice?

topaz mortar
#

Does anyone here actually use features like Steam login & Cloud Code Modules?
Been struggling with both for 3 days now, finally got most of it figured out but DAMN ... The docs are SO useless ...

lament silo
#

yea i have 2 pickaxes in hotbar

#

its unstackable

rich adder
lament silo
#

whereas if i had like 999 rocks it would have only 1 game object in itemholder

rich adder
topaz mortar
#

oh there's a channel for that 😮

rich adder
#

you'd have to debug. SpawnNewItem item correctly

#

there isn't something obvious im noticing yet

lament silo
lament silo
#

not 2

rich adder
#

well what is the condion that activates 1 or 2

#

there probably isnt a solid check to ensure only 1 item is held

lament silo
#

yes thats my question

#

which check do i put so only 1 pickaxe appears

rich adder
lament silo
#

like 5

#

the link is not generating for me

rich adder
# lament silo like 5

thats a look ot scripts to look thru, dont u know which ones are more relevant . You've built it no?

lament silo
#

yes this one is more relevant

Item selectedItem = GetSelectedItem(false);
        foreach (Transform item in itemHolder)
        {
            ResourceItem resourceItem = item.GetComponent<ResourceItem>();
            IEquippable tool = item.GetComponent<IEquippable>();

            if (selectedItem != null && selectedItem == resourceItem.item)
            {
                equippedItem = item.gameObject;
                equippedItem.SetActive(true);
                tool.Equip(itemHolder);
            }
            else
            {
                item.gameObject.SetActive(false);
                tool.Unequip();
            }
        }
#

its a switch between item models

#

like from pickaxe to rock

rich adder
#

you probbaly wantto break then once one of the items is set or something

#

this whole system already looks frail

#

how do you set selectedItem

lament silo
#
public Item GetSelectedItem(bool use)
    {
        InventorySlot slot = hotbarSlots[selectedSlot];
        InventoryItem itemInSlot = slot.GetComponentInChildren<InventoryItem>();
        
        if (itemInSlot != null)
        {
            Item item = itemInSlot.item;
            if (use)
            {
                itemInSlot.count--;
                if (itemInSlot.count <= 0)
                {
                    Destroy(itemInSlot.gameObject);
                    Destroy(equippedItem);
                    equippedItem = null;
                }
                else
                {
                    itemInSlot.RefreshCount();
                }
            }
            
            return item;
        }

        return null;
    }
amber spruce
#

i think its to do with how my enemy moves

rich adder
lament silo
#

it only switches to first object in itemholder

#

cant switch out

rich adder
#

wdym?

lament silo
#

checkmark is a rock

#
if (selectedItem != null)
            {
                equippedItem = item.gameObject;
                equippedItem.SetActive(true);
                tool.Equip(itemHolder);

                break;
            }
```this is all i did
sonic remnant
timber tide
#

You're setting active to your text a few places so I suggest figuring out why if it's the problem

sonic remnant
#

yes but still can't figure out why it is activating when i open and close the inventory screen / crafting screen.

timber tide
#

I suggest adding Debug.Log to each place you activate your text then maybe youll figure out where

runic dome
#

Hi ! I don't see my function I just created, why that ?

rich adder
#

method has to be public

#

Yu have 4 console errors ur ignoring..

runic dome
#

This is the console error

rich adder
#

also google how to remove the Collab warning

#

you have to disable it in project settings

humble lantern
#

Hey all, I'm not sure how to search for my problem but here's the gist:
I have two types of ScriptableObjects, WeaponData and RuneData, both have the same attribute of itemType which defines what kind of Item they are. I want to be able to have one field in the inspector to put either ScriptableObject in, and for it to assign attributes based on the itemType in a script called Item.
How do I generalise the "public WeaponData weapon" and "public RuneData rune" into one "public ScriptableObject item"? is that possible? is there a better way maybe?

runic dome
#

have the same code as him but still manage to have error

languid spire
# runic dome

One big difference, he saved his code and you didn't

runic dome
#

I spammed control + S

#

file + register

languid spire
runic dome
#

i did this 20 times

#

ctrl+S

rich adder
eternal falconBOT
runic dome
#

if i say that i saved it means i saved

sonic remnant
# timber tide I suggest adding Debug.Log to each place you activate your text then maybe youll...

To fix the issue, I updated the Update method in the SelectionManager script. The solution involved resetting the text of interaction_text to an empty string whenever no interactable object is targeted. This ensures that the item name is cleared from the UI when the player is not focusing on any interactable objects. The code now checks for the absence of a target both when the raycast hits something and when it doesn't, ensuring that the item name is properly reset in all scenarios.

languid spire
rich adder
runic dome
#

so ? i didn't saved ?

languid spire
runic dome
#

yes he finished

ancient shadow
#

Yours says namepace not namespace

#

Small typo

ivory bobcat
#

Make sure to configure your ide. It is necessary to acquire help on the server.

polar acorn
runic dome
#

bro so help me instead of wasting time writing useless stuff

languid spire
fluid remnant
runic dome
#

i'm french and i have a bad english, you guys just pissing me of rn i want to break my desk

languid spire
runic dome
fluid remnant
languid spire
#

no more help for you until you prove you have a configured ide

frosty hound
#

You've been told exactly the issue throughout this entire conversation and linked to it again.

polar acorn
eternal falconBOT
amber nimbus
#

Hello, I am working on multiplayer tank game, and I have this code for despawning the tankObject and spawning some particles when it dies. If a client calls the DestroyTankServerRpc() it all works fine but if the host calls it I get
[Netcode] Deferred messages were received for a trigger of type OnSpawn with key 30, but that trigger was not received within within 1 second(s). UnityEngine.Debug:LogWarning I am not sure what causes the warning

eternal falconBOT
amber nimbus
rare basin
eternal falconBOT
amber spruce
#

how do i set a objects velocity to 0

rare basin
#

rigibody.velocity = Vector3.zero

#

and anuglarVelocity if you also want to set it to 0

#
rigidbody.velocity = Vector3.zero;
rigidbody.angularVelocity = Vector3.zero;
amber spruce
#

ok thanks

rare basin
#

In most cases you should not modify the velocity directly, as this can result in unrealistic behaviour tho

amber spruce
#

well im trying to have a thing launch the enemys but since they are moving they dont get pushed back far unless i set theforce amount super high and then they just get launched super high up

#

so if i set their velocity to 0 right before it should be better i think

rare basin
#

A physical object would usually not stop dead suddenly

#

if you want realistic behaviour

#

imagine car going 50mp/h and in 0.01s it just suddenly stops

amber spruce
#

still doesnt work they barely move

rare basin
#

🤷

amber spruce
#

any ideas how to make it work better

rare basin
#

we cant help without any context

amber spruce
#
targetRb.AddForce(launchDirection.normalized * launchForce, ForceMode2D.Impulse);

thats the code to launch them

summer stump
#

That will override addforce

#

Show ALL the code so we can have more context

amber spruce
#
Vector2 movement = direction * moveSpeed;
movement.y = rb.velocity.y;
rb.velocity = movement;

thats the part where the enemy moves

rich adder
#

yeah you're overriding

#

you can't use both

amber spruce
#

so what should i be using

sharp wyvern
#

either JUST use AddForce to change thier velocity, OR set the velocity directly

amber spruce
#

is there a way to only apply velocity to a certain axis

#

like just the x axis

rich adder
#

you know how a vector2/3 works right ?

sharp wyvern
#

direction.y=0; AddForce(direction*force); would apply NO force in Y axis

amber spruce
#

not really

sharp wyvern
#

err Y, sorry

rich adder
#

its just 2 or 3 floats

#

depending if its Vector2 or Vector3

#

X,Y,Z

amber spruce
#

so since im making a 2d game shouldnt i always use vector2

rich adder
#

both work the same

#

if you type vector3 into a vector2 Unity doesn't care

#

it just put 0s at Z

#

you just can't do V2 + V3

sharp wyvern
rich adder
sharp wyvern
#

Then I'd recommend you go with Vector2, just to keep it consistent.

weary moss
#

when you disable a game object, does its script get disabled too?

#

like the component

sharp wyvern
weary moss
#

alright thanks

amber spruce
#

how would i have it edit a variable for the other object

#

basically it would make it so the other object cant run

amber spruce
#

wait actually cant i just freeze the x instead

rich adder
amber spruce
#

im trying to make it stop moving right before you luanch them so it actually launches them and they dont just push tyhrough it

rich adder
amber spruce
#

so bascially i have a wave of enemies attacxking the player the player has a move that repels enemies but it moves them like a inch rn i want them to get launched furthur

rich adder
#

if you want AddForce to affect them you have to temporarly disable any part of the script with .velocity =

#

I would use a bool for .velocity like (isStunned ) or w.e , and a coroutine to push AddForce

dense root
#

How do I add AI to my PONG second paddle?

rich adder
dense root
#

I guess a related question is what's a good resource for it?

#

No it's me controlling it

rich adder
#

What I do is make it roughly follow the Y of the ball

#

and sometimes Add Random Speed accelerations for fake "dumbing down"

timber tide
#

i'd calculate the angle or direction of the ball and move the paddle accordingly

rich adder
#

Eg if ball is approaching start lining yourself up, and depending on difficulty add more and more imprecision

dense root
#

Hmm maybe AI is a bit outside my comfort zone... can you recommend a different modification? I'm still learning but I want to mod the game

timber tide
#

AI = move paddle depending where the ball is at

#

if you got this far you can do it

dense root
#

Definitely looks solid to me

rich adder
#

literally rn. this should give you basic start ```cs
[SerializeField] private Rigidbody rb;
[SerializeField] private Ball ball;
private void FixedUpdate()
{
var dir = ball.transform.position - transform.position;
dir.Normalize();

    rb.velocity = new Vector3(0, dir.y * 7, 0) ;

}```
#

I have anotherone with the AI I described b4 with random movespeed

amber spruce
#

anyone know why the animation still plays?

 private IEnumerator BounceTowardPlayer()
 {
 
     while (true)

     {
         yield return new WaitForSeconds(1.5f);

     if (isGrounded)
     {
         if (!IsStunned)
         {


             animator.SetTrigger("Jump");
             yield return new WaitForSeconds(0.6f);
             Jump();
         }
     }
     }
 }
amber spruce
#

like they are stunned but it still plays the animation

rich adder
#

it also depends how many times you actually called this routine

rich adder
amber spruce
#

because i also have that for if they can move and they dont move but the animation plays

rich adder
#

I dont understand

#

Put a Debug.Log inside the trigger code part then

#

verify thats not the source of issue

#

if you keep seeing debug then its running

amber spruce
#

huh so i stop seing the debug

#

i found the issue

#

when unity crashed yesterday and reset stuff i forgot to remake the animator

#

now it works lol

dire marlin
#

What's the equivalent of the walk of shame in the unity development community

#

Because I've been coding with chatgpt and now I'm scared to ask for help fixing my nonsense script

rocky canyon
#

that'd be it..

dire marlin
#

knew it

#

I am trying to create a UI element that is basically an editable to-do list. I was going to just use unicode checkboxes but it didn't want to do that, so I went ahead and made my sprites for it, set those up as prefabs. The checkboxes spawn in with the list entries. when I try to delete list entries with right click, the corresponding checkboxes are never destroyed.
https://gdl.space/raw/xixeyadago

languid spire
rocky canyon
#

ur best bet is to pretend u didnt say it was chat gpt code.. and just ask like u woulda had u wrote it on ur own..

#

and make sure u go and fault chatgpt, let him know the trouble he's caused by giving u code snippets w/o explaining to u why they do what they do

dire marlin
#

So far this is going just about as expected

latent spire
#

Anyone know why Content Size Fitter on TMP_Text isn't updating when adding space? " "

dire marlin
eager elm
queen adder
#

here my health as TextMeshPro
and in my gameManager i have

  // UI prefabs ===============================================
    public TextMeshPro scoreText;
    public TextMeshPro healthText;

but i cant drag and drop the Health object in the inspector? im not sure why this is not working

rocky canyon
#

u need ^ or TMP_Text

queen adder
#

legends, thanks

humble lantern
#

should I use array.Length or array.Count? it throws an error for Count and it can't find Length..

short hazel
#

Arrays have Length, they don't have Count

#

Assuming you mean "array" as something like GameObject[]

humble lantern
#

yeah thats exactly what I wrote in my code

short hazel
#

Make sure you wrote the name correctly, with correct capitalization

#

length is not the same as Length for example

humble lantern
#

gives me "Object reference not set to an instance of an object Inventory.isFull() with this code:

#

wait

summer stump
#

This is not configured
!ide

eternal falconBOT
short hazel
#

Please do that, you'll get errors in the code, as well as suggestions for names as you type

delicate venture
#

Hey guys
Sorry in advance for my poor knowledge and english (non native english speaker here) but i just started making a game from scratch and i came across with this problem, so im not really into coordinates cuz im getting started in programming so i used a code from a tutorial i saw on youtube, for context the MC is set to 45 X Rotation, the problem is when i press the "S" Key he just goes floating to the space lol
So i was expecting i could get some help

sharp wyvern
humble lantern
#

is that how I instantiate it?

sharp wyvern
wintry quarry
sharp wyvern
# humble lantern is that how I instantiate it?

that is just an example, but yes, it's an example of how to ionstantiate an array of 10 GameObjects. But I don't know if you actually need 10, or when woudld be an appropriate place for you to do that.

summer stump
sharp wyvern
#

^ no

rare basin
#

yes

#

you dont instantiate nothing

sharp wyvern
#

my examle is how to INSTANTITE is

rare basin
#

no it is not xd

sharp wyvern
#

ok

rare basin
#

items = new GameObject[10]; this is initialization

summer stump
#

You don't create any gameobjects with what you did glurth
You just initialize an array

humble lantern
#

I'm not good with terms, can I substitute a number with an int when declaring the size?

sharp wyvern
#

I instantiated an array. perhaps you mean rthe gameobjects?

humble lantern
#

does that have to go in the Start function? having a hard time wrapping my head around what goes where

summer stump
delicate venture
wintry quarry
#

well you instantiate both but you UnityEngine.Object.Instantiate the GameObjects whereas you use new to instantiate the array

sharp wyvern
#

no, intitalizing an array is fi;lling it with values.

eager elm
rare basin
summer stump
sharp wyvern
#

Instatiate: allocate memory for an object, create a refernce to it. Initialze: fill with a specific value

delicate venture
weary moss
#

how can i make an objects transform.position match the speed of a texture offset on a quaternion model?
I'm making a 2d endless runner game, where the background is just a 3d model with a texture that gets a constant offset to make the impression that everything is moving, parallax and all that. But i just can't find a way to sync the obstacle's speed to match the background offset speed, is there a way for me to do that?

eager elm
sharp wyvern
summer stump
delicate venture
rocky canyon
#

parent is a root object, the objects (parented) to it are children.. they follow around that object (scale, position, etc)

delicate venture
#

oh ok like a "chain" then
got it

spiral narwhal
#

I'm trying to add a smooth camera lookaround. This works, but it jumps from position to position and only seems to know four directions for some reason:

    private const float LEFT = -2.12f, RIGHT = 2.12f, TOP = 1.16f, BOTTOM = -1.13f;
    private Camera _camera;
    
    private void Start()
    {
        _camera = GetComponent<Camera>();
    }

    // Update is called once per frame
    void Update()
    {
        var mousePosition = Mouse.current.position.ReadValue();
        var inWorldPosition = _camera.ScreenToWorldPoint(mousePosition);

        transform.position = new Vector3(
            Math.Clamp(inWorldPosition.x, LEFT, RIGHT),
            Math.Clamp(inWorldPosition.y, BOTTOM, TOP),
            -10
        );
    }
rocky canyon
#

im confused.. a look would be a camera's rotation..
what i see here is you modifying the Transforms position.. (moving the camera around) vs rotating the camera around

spiral narwhal
#

It's top down 2D

#

Where LEFT is the limit to the left side, right to the right and so on

rocky canyon
#

oh okay so u do want the camera to move around

spiral narwhal
#

Exactly, based on the cursor position

#

Ohhh I found the error

#

It should be ScreenToViewportPoint and not ScreenToWorldPoint

rocky canyon
#

Nice!

delicate venture
hidden bone
#

in unity, how do i see multiple scenes in the editor? i can only see the one im currently editing

summer stump
hidden bone
#

thx

chilly vigil
#

!code

eternal falconBOT
tired needle
#

Anyone know any good guides or tutorials for making a simple dungeon/room generator in 2d?

chilly vigil
wintry quarry
chilly vigil
#

for post proceesing

wintry quarry
eternal needle
#

This must be the least amount of context I have seen in a question

wintry quarry
# chilly vigil

it's either a bug in the package or you misconfigured your scene / postprocessing settings somehow

#

In the former case - make sure you have the most up to date version oft he package and/or submit a bug report
In the latter case - fix your settings

chilly vigil
#

prevent me from running my game i think

wintry quarry
#

that's a runtime error

chilly vigil
#

wanna see my post processing settings

wintry quarry
dense palm
#

Hey, idk is it good channel, but I have a question regarding canvas. I want to place background image in Canvas(so it doesn't move) but is there a way to move it behind all the other sprites?

summer stump
dense palm
#

ok

zealous oxide
#

hey friends. i'm trying to designate a random gameobject(specifically its transform) from a list made by objects that are within a overlapcircleall as a "chosen" object, but im unable to find the right syntax to get this working

summer stump
zealous oxide
weary moss
#

Is the Debug.log ran on unscaled time?

wintry quarry
weary moss
#

like, if i run a Debug.log on my update, will the log stop if time stops?

wintry quarry
#

Update runs every frame

#

Regardless of time scale

#

Changing time scale doesn't affect framerate

slender sinew
#

Good to understand that if it did stop, it would be because Update wasn't running, not because of anything related to Debug.Log

weary moss
#

alright

wintry quarry
#

Yes, this question has nothing to do with Debug.Log it's really about time scale and Update

weary moss
#

but another question

#

i made these variables and debugs to check if time was accelerating(the game getting harder), and the debugs work and all of that but the accelerated one seems to be passing time slower than the unscaled one.
"Tempo puro" = unscaled time
"Tempo acelerado" = accelerated time

eternal needle
weary moss
#

yes, but slowly

#

but still shouldn't the debugs answer accordingly?

eternal needle
# weary moss yes, but slowly

I dont know what you're specifically trying to do with that, but you shouldnt do it like this.
Your time.deltaTime depends on the time scale, which is why unscaled time exists.

weary moss
#

like the accelerated one counts faster or something

short hazel
#

As time scale is higher, deltaTime will be lower. FixedUpdate for example will get called more frequently, resulting in fixedDeltaTime to be lower. Unscaled delta time will stay the same, as its name suggests, it's not affected by time scale

weary moss
weary moss
#

the time in between gets faster

eternal needle
#

Well first thing, you are increasing the timescale a small amount per frame. So someone on very high fps would have different gameplay from someone on low fps

weary moss
#

so i multiply it by deltaTime?

wintry quarry
#

unscaled i would say for this...

weary moss
eternal needle
#

I'd still say you shouldnt be using timescale like this at all, itd make more sense to just have a separate object which exists as a scaling factor in your game.

weary moss
#

so i should create an object that scales and then multiply everything that should scaled by it?

eternal needle
weary moss
#

The game is like a 2d subway surfers, so i need everything to accelerate over time

wintry quarry
#

I don't really think subway surfers accelerates with time scale

#

the movement speed of the player just increases

weary moss
#

cause its 3d probably

wintry quarry
#

what difference does 2d vs 3d make

weary moss
#

in 2d i'm doing a texture offset thingy to make the background seem like its moving

#

and the player doesn't really move

wintry quarry
#

you can just increase the speed of that movement then

#

again no need for time scale

eternal needle
wintry quarry
#

Note for example in this video:
https://www.youtube.com/watch?v=7ghSziUQnhs

  • The falling snow speed does not increase
  • The train movement speed does not increase
  • the spinning speed of the coins does not increase.

The only thing increasing is the player movement speed

weary moss
verbal dome
blazing charm
#

I'm trying to create a temporary buff for my player when an item i picked up.
This is the code I'm using for my item:

using UnityEngine;
public class AttackPotion : MonoBehaviour
{
    [SerializeField] int bonusDamage;
    [SerializeField] float duration;

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.CompareTag("Player"))
        {
            if (PlayerStats.Instance.bonusDamage <= 0)
            {
                StartCoroutine(PlayerStats.Instance.ApplyBonusDamage(bonusDamage, duration));
            }
            else
            {
                PlayerStats.Instance.potionGreen++;
            }
            AudioEffectsManager.Instance.PlayPotionSound();
            CollectableUI.Instance.UpdatePotionGreenText();
           Destroy(gameObject);
        }
    }
}```
THe Coroutine ApplyBonusDamage() looks like this: 
```cs
public IEnumerator ApplyBonusDamage(int damage, float duration)
{
    Debug.Log("Starting buff!");

    bonusDamage = damage;
    Debug.Log("bonusDamage set to: " + bonusDamage);

    yield return new WaitForSeconds(duration);

    bonusDamage = 0;
    Debug.Log("bonusDamage reset to: " + bonusDamage);

    Debug.Log("Ending buff!");
}```

Th UI is updated and the bonudDamage is applied correctly. THe issue I'm having is that the bonusDamage is not set to 0 when duration seconds have passed (in the coroutine ApplyBonusDamage(). When I check the Debug-Log() output, I can see that onlt the ones before the WaitForSeconds() have been written to the concole.
eternal falconBOT
sharp jay
blazing charm
sharp jay
#

and on the backend of this. you should never start a coroutine like this on another object

#

instead, make a function that returns void, and start the coroutine in that. (the same script that has the coroutine)

#

and then in the class you need to start it: PlayerStats.Instance.ApplyBonusDamage(stuff);

blazing charm
# sharp jay Absolutely correct

Changed it around a bit and it now looks like this instead:

public void BonusDamage(int damage, float duration)
{
    StartCoroutine(ApplyBonusDamage(damage, duration));
}

public IEnumerator ApplyBonusDamage(int damage, float duration)
{
    bonusDamage = damage;
    yield return new WaitForSeconds(duration);
    bonusDamage = 0;
}

Works like a charm. 🙂 Thanks for the quick help.

twin bolt
#

I'm trying to set up bools for walking, crouch walking and running. Should i base them off of input or player velocity?

quasi rose
#

To me, these sound like all different states/input. Walk state, crouch state, run state, etc.

twin bolt
quasi rose
#

And what do you mean "issues with input"?

twin bolt
# quasi rose Can you share it?
        {
            StartCoroutine(isCrouch());
        }
        
        if(KBMinUse && KBMinUse && Input.GetAxis("Horizontal") == 0 || Input.GetAxis("Vertical") == 0)
        {
            isCrouchWalking = false;
            StopCoroutine(isCrouch());
        }```
#

if the coroutine is going for the 1 second, then the playing is crouchwalking.

quasi rose
#

Well your || Input.GetAxis("Vertical") != 0 could make the condition fire. You realize right?

twin bolt
#

Really? I'm checking to see if the key is being pressed.

quasi rose
#

I assume you want this only to fire when the player isCrouched right?

twin bolt
#

I want it to fire, when the player is crouched and is moving also.

quasi rose
#

First part you're checking if the player is crouched, kb in use, and if horizontal input is not 0. Second half of it you're asking it to fire if vertical is not 0.

#

So whether player is in crouch or not, as long as vertical is not 0, fire.

twin bolt
#

Oh wow, that was definitely not on purpose.

#

I'll fix that and check if it works.

twin bolt
quasi rose
twin bolt
#

The isCrouchWalking bool is true when both axises are being changed, but if just one is being changed, the bool flickers or doesn't change at all.

#

Basically if i click A and W, or S and D.

quasi rose
#

wait dude im tripping and so out of it today lol. I am correct (or going crazy), you need to repeat your conditions, otherwise you'll start the couroutine anytime that vertical is not 0. Which you dont want, you want the player to be crouched.

quasi rose
#

Can you share the full script?

twin bolt
#

Are you sure, it's long, and pretty messy?

quasi rose
#

all good

twin bolt
quasi rose
twin bolt
quasi rose
#

It's not about "neat" it's just that you're going at it the wrong way really. All these conditions and bools everywhere are just a cause for pain and confusion. Good for learning and starting small, but it's not manageable for larger projects. Give me a min..

amber spruce
#

how do i hide text via code

#

like i wanna just uncheck it

verbal dome
amber spruce
#

why cant i access functions from my script??

#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using Unity.VisualScripting;

public class UIController : MonoBehaviour
{
    public TextMeshProUGUI countdown;
  public void OnWaveEnd()
    {
    Debug.Log("Wave ended!");
        StartCoroutine(Countdown());
    }
    IEnumerator Countdown()
    {
        countdown.enabled = true;
        countdown.text = "5";
        yield return new WaitForSeconds(1f);
        countdown.text = "4";
        yield return new WaitForSeconds(1f);
        countdown.text = "3";
        yield return new WaitForSeconds(1f);
        countdown.text = "2";
        yield return new WaitForSeconds(1f);
        countdown.text = "1";
        yield return new WaitForSeconds(1f);
        countdown.enabled = false;
    }
}
#

i have them

verbal dome
amber spruce
#

thanks

rich adder
#
for (int i = 5; i > 0; i--)
        {
            yield return new WaitForSeconds(1f);
            countdown.text = i.ToString();
        }```
uncut crypt
#

Im having an issue where whenever I create an object its extremely small

verbal dome
uncut crypt
#

No

#

Just the basic create object

frosty hound
#

The basic primitives are 1m

uncut crypt
#

I have to scale it up to around 50 for it to be a normal size

frosty hound
#

So you're probably just far away ...

uncut crypt
#

I cant even zoom in to it

verbal dome
#

Sounds like everything else is just too big

#

Or yeah camera is far

uncut crypt
#

The camera literally cannot zoom in more

frosty hound
#

Click on it and press F

verbal dome
#

You can select an object and hit F while hovering the cursor on scene view

frosty hound
#

This isn't a coding issue either.

uncut crypt
#

oh yeah wrong chanel

#

When i click f its still minscule

verbal dome
#

Click F again

#

It's a toggle

noble urchin
#

Is there a way to check how long it took for a function to run? I have top watch in my function in nanoseconds but there's no seconds shown

quasi rose
summer stump
verbal dome
#

For quick measuring I usuall go with stopwatch.Elapsed.TotalMilliseconds

spiral narwhal
#

I'm using a UnityEvent like so
playerHandService.OnCardDrawn.AddListener(RenderNewCard);

This calls the method when a new card is drawn:

private void RenderNewCard([NotNull] Card cardEntity)
        {
            var newCardViewContainer = Instantiate(_cardViewContainerPrefab, transform);
            _drawOffset++; // <-------- THIS IS THE ISSUE
            StartCoroutine(CreateCardAfterTime(newCardViewContainer, cardEntity));
            DecreaseSpacing();
        }

        private IEnumerator CreateCardAfterTime([NotNull] CardInHandContainer container, [NotNull] Card cardEntity)
        {
            // Guarantee to wait one frame
            yield return null;

            // Now create a slight draw offset
            yield return new WaitForSeconds(0.1f * _drawOffset);

            container.CreateChild(cardEntity, this);
        }

What I intend to do is to use an offset as an integer that is incremented each time a card is rendered. This offset then increases the WaitForSeconds, which is supposed to create a typical "draw" effect. However, running this, all cards wait for the maximum offset of 5 * 0.1f = 0.5f and then render at the same time. Is this something about UnityEvents that I don't understand?

verbal dome
spiral narwhal
#

Ok I will try

queen adder
#

Hey everyone
Does anyone know how to achieve wall jumping?
The issue is, I'm able to make the 2D box jump from one wall to another back and forth
But I want my character to be able to jump along the same wall if the left arrow is held
I tried with trial and error
But it doesn't seem to be doing much

spiral narwhal
verbal dome
#

Using a local variable is key here

#

For example, your first coroutine starts, and after it has waited that one frame, _drawOffset was already changed to 5

spiral narwhal
#

So _drawOffset++; is executed five times before at least one Couroutine is started by unity, that's the issue?

verbal dome
#

Well the coroutine does start immediately but you have yield return null which causes the one frame delay

#

And during that delay all coroutines have started and _drawOffset has already reached 5

#

Make sense?

spiral narwhal
#

Ohhh yes! Totally, thanks for explaining! :)

verbal dome
#

If that's the case, you can try yield return new WaitForEndOfFrame() instead, which eliminates the frame delay but usually fixes that kinda stuff

spiral narwhal
#

Yes because of UI bugs. Ok I'll try!

chilly vigil
#

i am removing the post procesing to see if it help me

verbal dome
#

That's pretty random

chilly vigil
#

i remove the post processing from my game but i got ullReferenceException: Object reference not set to an instance of an object
UnityEngine.Rendering.PostProcessing.AmbientOcclusion.IsEnabledAndSupported (UnityEngine.Rendering.PostProcessing.PostProcessRenderContext context) (at Library/PackageCache/com.unity.postprocessing@3.2.2/PostProcessing/Runtime/Effects/AmbientOcclusion.cs:183)
UnityEngine.Rendering.PostProcessing.PostProcessLayer.SetLegacyCameraFlags (UnityEngine.Rendering.PostProcessing.PostProcessRenderContext context) (at Library/PackageCache/com.unity.postprocessing@3.2.2/PostProcessing/Runtime/PostProcessLayer.cs:816)
UnityEngine.Rendering.PostProcessing.PostProcessLayer.SetupContext (UnityEngine.Rendering.PostProcessing.PostProcessRenderContext context) (at Library/PackageCache/com.unity.postprocessing@3.2.2/PostProcessing/Runtime/PostProcessLayer.cs:911)
UnityEngine.Rendering.PostProcessing.PostProcessLayer.BuildCommandBuffers () (at Library/PackageCache/com.unity.postprocessing@3.2.2/PostProcessing/Runtime/PostProcessLayer.cs:558)
UnityEngine.Rendering.PostProcessing.PostProcessLayer.OnPreCull () (at Library/PackageCache/com.unity.postprocessing@3.2.2/PostProcessing/Runtime/PostProcessLayer.cs:487)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)

#

i think i have remove it from the package manager

verbal dome
#

Yes

unreal imp
#

I want to make it softer

verbal dome
unreal imp
#

uh sorry

#

I love you all guys, I don't know what I would do without all of you ❤️

#

ejem sorry

modest barn
#

Is this notice about no MonoBehaviour scripts OK? I'm not using MB but I'm not sure if this is simply a notice or something that Unity isn't happy about

wintry quarry
#

Fix all compile errors and make sure the filename matches the class name

#

you also forgot : MonoBehaviour

modest barn
#

The app builds fine

wintry quarry
#

if it's not suppsoed to be a MonoBehaviour then it's fine

#

that's all the message is saying - there is no MonoBehaviour in the file

modest barn
#

Coolio

#

Thanks

modest barn
wintry quarry
#

Typically red == error

#

white == info

formal escarp
#

Hey guys i have a question .I have a script which compares the tag of my player and checks if it collides with an object, when colliding it should activate the canvas to put on a screamer. but it does not work. i am not sure what im doing wrong.

wintry quarry
#

adding log statements to your code is the first step.

#

this will tell us which parts of the code are running or not

formal escarp
#

Thats why i am not debugging.

wintry quarry
#

debugging is the only way to find the answer for sure

#

otherwise you are just guessing

#

don't think you can skip it for XYZ reason

formal escarp
#

i think i already know what the problem is.

wintry quarry
#

you will always find the answer fastest by debugging systematically

formal escarp
#

without even checking. i think i forgot to put "Is Trigger" 💀

#

thats weird, not sure why but that specific object was created without a box collider.

#

even tho it was made out of a box.

verbal dome
#

It only has a box collider by default if you create it with GameObject > 3D Object > Cube

uncut crypt
#

'WorldSaveGameManager' does not contain a definition for 'GetWorldSceneIndex'

The code in WorldSaveGameManager:
public int GetWorldSceneIndex()
{
return.worldSceneIndex;
}

wintry quarry
uncut crypt
#

Assets\Scripts\PlayerInputManager.cs(35,67): error CS1061: 'WorldSaveGameManager' does not contain a definition for 'GetWorldSceneIndex' and no accessible extension method 'GetWorldSceneIndex' accepting a first argument of type 'WorldSaveGameManager' could be found (are you missing a using directive or an assembly reference?)

#

if (newScene.buildIndex == WorldSaveGameManager.Singleton.GetWorldSceneIndex()

wintry quarry
#

if this is the actual code: return.worldSceneIndex; then WorldSaveGameManager itself has a syntax error in it

#

because that is not valid C#

uncut crypt
#

Do you know what the correct code to do that is

wintry quarry
#

return worldSceneIndex;

#

where did you get the idea you want a dot there?

uncut crypt
#

unsure

#

following a tutorial but thats not even what he typed

#

All errors gone thank you

modest barn
#

How do I save a large array to a json file?

wintry quarry
modest barn
#

I know I'm meant to use jsonserializer but I can't find docs

#

Never mind I found it, sorry

wintry quarry
modest barn
#

Also, how can I find out which version of .NET my Unity editor is using?

#

It's Unity version 2022.3 but I'm not sure which version it uses, Googling just gives .NET Standard 2.1 which isn't what I'm looking for

wintry quarry
#

What are you looking for

modest barn
#

Do I have to change this?

wintry quarry
#

to do what?

modest barn
#

I just want to know which one to select here

wintry quarry
#

What are you trying to accomplish with this info

wintry quarry
#

this is for general .NET

#

you're in unity

modest barn
#

I see, and Unity uses Standard?

modest barn
weary moss
#

what does multiplying something by Time.deltaTime really do? I mean i know that if i multiply something by it it will no longer be linked to the fps, but why is that?

buoyant knot
#

position in meters. acceleration in meters per second squared, etc.

modest barn
#

If someone's computer lags and there is a 1-second gap between frames. Let's say your player moves 1cm for every millisecond that a key is pressed down. For that frozen period, the player will have moved very far.

#

Multiplying by deltatime ensures that that doens't happen

buoyant knot
#

Time.deltaTime is the time that has elapsed in seconds within the last frame

rich adder
#

through diff fps

buoyant knot
#

not really, no

weary moss
#

ohhh

#

so, should i put it everywhere that has an operation that is dependent on frames for a smoother deal?

buoyant knot
#

if I want my character to move at 5 meters/second, and I am writing his position within a frame, you want to advance it by 5 meters per second, not 5 meters per frame

#

you need to do: position += velocity * Time.deltaTime

#

because Time.deltaTime is the amount of time in seconds elapsed in the last frame

summer stump
buoyant knot
#

the reason all these explanations aren’t quite right is; if you did this in FixedUpdate, the calculation should become framerrate independent (mostly). But the calculation is incorrect

weary moss
buoyant knot
#

FixedUpdate runs at fixed time intervals

summer stump
weary moss
#

alright

buoyant knot
#

imagine units on your numbers

weary moss
weary moss
rich adder
#

steady and predictable speeds of the frame rate

#

thats what exactly i said

buoyant knot
#

which is wrong

#

velocity doesn’t have units of m/s^2

verbal dome
#

Otherwise you would move the same amount per frame regardless of the frame taking 0.01 seconds or 1 second

weary moss
buoyant knot
#

your simulation advances by Time.deltaTime each frame. If you want to define a velocity in units/second, and convert that to a position within a frame, then you NEED to use deltaTime as the conversion factor to know how much time has passed.

weary moss
buoyant knot
#

and that isn’t to make it consistent. it’s because it is what makes it correct

#

if you DONT multiply by deltaTime, then you successfully defined your velocity in units/frame.

rich adder
#

steady and predictable
sounds like consitent to me 🤷‍♂️

buoyant knot
#

and if you want to define your velocity as units/frame, that’s cool. but that probably isn’t what you thought you were doing, and is therefore just wrong

buoyant knot
summer stump
buoyant knot
#

framerate can change, but that velocity is still units/frame. Consistent, but wrong

rich adder
#

that makes no sense

verbal dome
#

I think you both mean the same thing with just different wording of opposite things

#

Consistent across devices/framerates
Consistent per frame

#

Or "constant" per frame

#

I think I just made it even more confusing tbh

buoyant knot
#

let’s say I serialize a field for velocity, and the tooltip says “how fast we move over time.” If you don’t multiply by deltaTime, then it is a velocity in units/frame, which contradicts what the tooltip says. Because we aren’t advancing over time, but over frames.

rich adder
#

I just quoted the Unity Docs 🤷‍♂️ Ill take that explanation over any lol

uncut crypt
#

How can you find compiler errors

weary moss
#

could i remove the deltatime if i used "void FixedUpdate()"?

buoyant knot
#

it would still be wrong

#

it would work, and be wrong

weary moss
eternal needle
buoyant knot
#

because your units are not correct

verbal dome
# weary moss what is **"sometimes"**?

Lets say you move something manually with rigidbody.MovePosition you want to use deltaTime/fixedDeltaTime.
But when adding forces, you don't want to do that since it's already used with ForceMode.Force and ForceMode.Acceleration

buoyant knot
#

just check that your units are correct, and you will know exactly what is going wrong

uncut crypt
#

Nowhere in vsc does it say I have an issue

#

just unity

rich adder
eternal falconBOT
#
Visual Studio Code guide

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

https://on.unity.com/vscode

summer stump
buoyant knot
weary moss
#

so FixedUpdate is just if i want something that is not linked to the frame updates, but is also just running in it's own time?

buoyant knot
#

i gtg now, but if you don’t respect units, anything physics-related will make your life miserable.

rich adder
summer stump
weary moss
#

so if i have something that is moving, i should put it into FixedUpdate

#

or has a rigidbody

rich adder
weary moss
#

rigidbody is physics isn't it

rich adder
#

yea

summer stump
summer stump
weary moss
#

alright

rich adder
#

best look at the docs to get the full details

weary moss
#

never used anything physics related just transform until now

rich adder
#

translation will never give you accurate collisions

weary moss
#

but thanks for the help guys

#

wdym

#

if i use transform.translation the collision wont work

rich adder
verbal dome
#

Moving via transform will not notify the physics that the object moves

#

So collisions will be mostly ignored

#

Just weird glitchiness all around

rich adder
#

so they prefer physics movement/ timestep

weary moss
#

i mean, until now my collisions are working

#

i think

summer stump
rich adder
#

maybe you're moving too slow to notice

weary moss
#

alright, so should i use rigidbody.velocity instead?

#

that's physics ain't it?

rich adder
#

velocity is physics yes

#

AddForce works too

weary moss
#

but if my object doesn't have a rigidbody its still ok to use transform for as long as they aren't going a Mach God speed

rich adder
#

I still wouldn't take the chance

#

for any collision

#

you don't want your players to experience a bad time for inaccurate collisions

weary moss
#

my game has like one collision per game which will be the game over, can it still be messed up?

#

trigger

#

not collision

#

the collision part is made with a rigidbody

rich adder
#

triggers colliders are part of physics btw

#

as long as 1 rigidbody is there between the trigger/collision

weary moss
#

alright, i'll keep that in mind

#

thx

flint wind
#

heres my code

summer stump
#

Your flipX is false for greater AND less than 0

#

Oh wait

#

You do flipX in four spots

#

Maybe just remove the top two?

flint wind
#

same result

#

alright so I have it fixed but the rest position after going to the right remains looking left

verbal dome
#

Did you remove the top or bottom flipX lines?

#

Show current code

flint wind
verbal dome
#

After you fix that, move the rb.MovePosition line to FixedUpdate instead. That's where you should move rigidbodies, not Update

summer stump
# flint wind

Why did you change the bottom two when I said remove the top two?

flint wind
summer stump
verbal dome
#

Your video's behaviour doesn't match the code though... Is something else flipping it too?

#

Change it to what Aethenosity suggested first

ivory bobcat
#

The second if stuff is done after animation states - they aren't doing anything.

#

But maybe I'm wrong UnityChanHuh

modest barn
ivory bobcat
#

What's an sr? I'm assuming some sort of renderer..

uncut crypt
flint wind
modest barn
# uncut crypt console

In your editor. At the bottom. You have two tabs, one that shows all your folders and files and Assets, the other tab called Console.

flint wind
#

whoops I did something wrong