#šŸ’»ā”ƒcode-beginner

1 messages Ā· Page 779 of 1

mild furnace
#

Is that also responsible for showing the asset references near the class definition?

gloomy heart
#

yes, i have a main DB class that stores all the const variables and the file is some lines long but it goes for each variable and its too hard to see the actual declared variable

naive pawn
#

it seems like the references one is from c# and the serializedfield is from unity, so they should be separately configurable i think

mild furnace
#

Restarting now, that seems to be the fix!

naive pawn
#

though, "Unity Message" here is probably from the same provider. i don't think it'd have that amount of granularity to enable that but disable the serialized field one

mild furnace
#

"Look at all this functionality guys! Here, have some functionality!" - Unity probably

naive pawn
mild furnace
#

Under Unity, its Enable Code Model

naive pawn
#

this one, right?

mild furnace
#

ya

naive pawn
#

well, it says it does something for Hover too, so... not sure what that entails. thought hover stuff would be handled just through c# docs

mild furnace
#

I'm sure it could be useful but I'd like some extra settings on there,
maybe there could be a place for feedback on that

naive pawn
#

well, at least i found out what to blame for... messages autocompleting halfways

tired sandal
#

which channel can i ask for help?

slender nymph
mild furnace
#

I disabled code model and performance got worse

#

Its using all my cpu again when tabbing back into the editor and trying to play

naive pawn
#

huh, that's weird. i'd think it'd be doing less

gloomy heart
#

Why are my scripts just gone

naive pawn
#

maybe it lost its cache after the restart?

naive pawn
gloomy heart
#

The entire Scripts folder is gone

naive pawn
#

could be any number of things, none of which would be related to unity specifically

polar acorn
#

What does it look like in the file browser

naive pawn
#

or something else did. is your project in onedrive

gloomy heart
#

They're back suddenly, im using git from now, can't lose them after this incident also my ssd sapce is low

gloomy heart
restive canyon
#

guys if i want to create a building system like scrap mechanic alone is it even worth trying im a beginner or should i just give up on it, i find like 0 tutorials on it

polar acorn
#

You are unlikely to find tutorials on how to make exactly the game you want to make. The point is to actually learn how the systems work and synthesize new information from multiple sources

naive pawn
#

why is it possible to change the value of one

wicked cairn
radiant voidBOT
restive canyon
#

just a stupid question if i watch alot of tutorials and just do them and try to learn will i even learn?

naive pawn
#

if you only copy tutorials you won't learn

#

you gotta treat tutorials as learning resources rather than just following them blindly

polar acorn
#

Learning isn't something that just happens. You have to actually put in effort.

restive canyon
#

oki

#

why dosent this work if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
{
rb.linearVelocityY = 2f * jumpPower;
}

naive pawn
#

define "doesn't work"

#

are you getting an error

restive canyon
#

my 2d character isnt jumping i have a working groundcheck and all that

naive pawn
#

are you getting an error

polar acorn
restive canyon
#

lemme check

polar acorn
#

Try logging the values before you check them

restive canyon
#

lol my brain is dead i didnt call the function

ivory bobcat
# restive canyon just a stupid question if i watch alot of tutorials and just do them and try to ...

Depends. You'll probably pick up minor patterns like the Unity callback functions (Start, Update, etc), control statements (if/case statements, loops etc) and properties of certain types by repetition but unless you're actually aware of why these statements are a solution to the particular problem.. you'll likely not be able reuse what you've seen elsewhere.

What exactly are you trying to learn?

restive canyon
#

im just honesty trying to learn how to make games without searching up every single part and solve things myself

#

oo my code worked

#

yay

ivory bobcat
#

So.. are you trying to learn the unity api, programming in general, how others approach game development problems, how a certain feature is implemented, the game development life cycle or ...?
Game development is a very broad subject and overlaps a large array of skills. It's normal to lookup/learn new things you've never seen or implement before.

restive canyon
#

Well Unity game development, i want to be able to make games on my own and in the end maybye release them on steam. I can do gameart so thats fine. but the part im tring to learn is understanding unity so for an example i dont have to look up "how to make a 2d movement script" so i can just come up with it myself

wintry quarry
ivory bobcat
#

Alright, so repetition. Just be aware that it's normal to lookup the docs or tutorials for behaviors like the input system as changes are common with updates.

mint flicker
#

Hey i need some Help is there Logical way to make the camera not fly across i have two cameras and the one on the other side swings depending on wich way you enter

timber tide
#

set the position of the camera

wintry quarry
mint flicker
#

it has code

wintry quarry
#

Then maybe share the code!

mint flicker
#

yes

mint flicker
timber tide
#

well, would like to see code but if you're just juggling virtual cameras then it will always lerp to the next priority

mint flicker
#

oh i will serch lerp

timber tide
#

nono, it lerps it for you already

mint flicker
#

ohh

wintry quarry
mint flicker
#

blends yes i will reserch

wintry quarry
#

assuming you're switching cinemachien cameras here

mint flicker
#

yes

final fjord
#

Can I get eyes on a code I made for a ā€˜potion making’ sim? It’s a script meant to recognize items as ā€˜ingredients’ and change the potion color accordingly and also make a potion when given the correct ingredients and delete the ingredients when they collide with the cauldron

#

(Sorry that may sound supper convoluted)

silk night
naive pawn
#

!code

radiant voidBOT
final fjord
#
using UnityEngine;

public class CauldronTrigger : MonoBehaviour
{
    [Header("Liquid")]
    public Renderer liquidRenderer;         // The material that will change color
    public Color defaultColor = Color.black;

    [Header("Ingredient Colors")]
    public IngredientColor[] ingredientColors;

    [Header("Potion Crafting")]
    public string ingredientA = "Herb";
    public string ingredientB = "Crystal";
    public GameObject potionPrefab;
    public Transform spawnPoint;

    private bool hasA = false;
    private bool hasB = false;

    private void Start()
    {
        if (liquidRenderer) 
            liquidRenderer.material.color = defaultColor;
    }

    private void OnTriggerEnter(Collider other)
    {
        // Check if it's an ingredient
        IngredientData ingredient = other.GetComponent<IngredientData>();
        if (!ingredient) return;

        // Change liquid color if this ingredient has a color defined
        foreach (var entry in ingredientColors)
        {
            if (entry.ingredientName == ingredient.ingredientName)
            {
                liquidRenderer.material.color = entry.color;
            }
        }

        // Track crafting ingredients
        if (ingredient.ingredientName == ingredientA)
            hasA = true;
        if (ingredient.ingredientName == ingredientB)
            hasB = true;

        // If both are present → make potion
        if (hasA && hasB)
        {
            SpawnPotion();
            hasA = false;
            hasB = false;
        }

        // Destroy the ingredient that fell in
        Destroy(other.gameObject);
    }

    void SpawnPotion()
    {
        if (potionPrefab && spawnPoint)
            Instantiate(potionPrefab, spawnPoint.position, spawnPoint.rotation);
        else
            Debug.LogWarning("Potion prefab or spawn point missing.");
    }
}

[System.Serializable]
public struct IngredientColor
{
    public string ingredientName;
    public Color color;
}
#

sorry- im a student and specialize in 3d modeling not really code

#

The issue is that literally none of it is functioning, the potion isnt changing colors, it isnt deleting ingredients, and it isn't creating the prefab its given

slender nymph
#

what calls SpawnPotion? ah nevermind, is see this inside OnTriggerEnter now
also for making sure OnTriggerEnter is called go through these troubleshooting steps: https://unity.huh.how/physics-messages

final fjord
#

does this look correct for my purposes?

slender nymph
#

the link i sent walks you through all of the things you need to check, so just pay attention to it

wintry quarry
#

(I am just jumping in at the end here so idk if that's relevant but I bet it's not intended)

final fjord
#

yeah i fixed them so they're emission instead of base

final fjord
dry anchor
#

Is there a good way to decouple your input code from a player script? I was trying to use events, but I'm still kind of new to the input system so I kept getting errors. Also when I perform a jump action, I know that functionality should go into FixedUpdate method since I'm using a rigidbody, but I'm not sure how to implement that without making my code a mess. Any suggestions would be appreciated thanks.

wintry quarry
#

But even if it was, all you have to do is store the player's intent to jump in a variable and consume that intent in FixedUpdate

#

Also I'm not really seing anything in here that needs decoupling

#

you are already using events.

dry anchor
#

I was just trying to have the input functionality in a different script

#

instead of inside the player script

#

using an event but I kept getting a null reference error

wintry quarry
#

and why you feel it needs to go in a different script?

dry anchor
#

I'm still new to unity and was just trying to recreate Flappy Bird since I figured it would be an easy project

wintry quarry
dry anchor
#

The only input I have rn is a mouse left button down

wintry quarry
dry anchor
wintry quarry
#

Flappy bird is very simple. I don't see why you'd want to complicate it with extra scripts

wintry quarry
#

the script you shared doesn't do anything except that

#

so what would be left in this script when you remove that?

#

that's literally the one thing this script is doing

dry anchor
#

I'm just starting the project. I was just trying to make the code clean

#

Figured it would be nice to have that functionality in different scripts

wintry quarry
#

In different scripts from what?

#

there's nothing else in this script

dry anchor
#

One for input from the input actions and a seperate one for just player functionality

wintry quarry
#

you don't have any input code here

#

you have player functionality here

dry anchor
#

Its because I did the C# generate option for the new input system

wintry quarry
#

But if you really wanted to just remove any and all mentions of "input" from here, you could just make this exact code but instead of calling the Rigidbody stuff directly, you call a function on a separate player script

dry anchor
#

There's like 5 different approaches

wintry quarry
#

I'm well aware

wintry quarry
#

but what you're describing is ultimately just "call a function on another script".

dry anchor
wintry quarry
#

And again, if you need help with a specific error you would have to share the specific code you tried

#

I can't help you with a vague error without seeing the code that caused it

#

As you can see this is almost twice as much code to do the same thing (and you need to attach two scripts)

#

not worth it when the script is so simple

dry anchor
#

I was just trying to follow good coding principles and not mix up code even if the project is simple. Let me revert my code back to what I had and then I'll post what I had initially

wintry quarry
wintry quarry
# dry anchor https://paste.mod.gg/nngxawpfjoqh/0

This code has a race condition with the two Awake methods. If the GameInput one runs first, you will get an NRE when you try to do:
_inputActions.Player.FlyUp.performed += Player.Instance.FlyUp; because Player.Instance won't have been assigned yet.

I think using a singleton pattern for this reference is poor practice

#

These are presumably two components on the same GameObject. There's no reason not to use normal Unity dependency injection such as a serialized field or GetComponent

dry anchor
#

Yea it looks like the Awake methods were the issue thanks. Yea the singleton pattern was probably unnessary I could of just created a simple instance like you did

edgy sinew
#

Hi all, I am wondering what is your recommendation to solve weapon aiming/equipping, likely with IK, using code?

Thus far I have written some basic IK / armature related code,
Like for attaching an item to armature hand onto a specific point on the item, with some specified rotation (Euler angles), etc
Indicating where to attach the left hand onto said weapon, if item requires two handed equip
(assign target position every frame, since "change target GameObject of IK" required Rig re-building and such.)

An issue has come up with aiming, where, the animations move the item too much, for example steadily aiming a 2-handed rifle,
Though I have had some success avoiding animations altogether and simply assigning OverrideTransforms to "aim" an item.
Thank you

timber tide
#

for one I wouldnt use eulers

frosty yarrow
#

i have a problem in my code tht's the enemy when hits the ground the score doesn't go up
enemy script: using UnityEngine;
using UnityEngine.UI;
public class enemytestcode : MonoBehaviour
{
float minx = -8.5f;
float maxx = 8.71f;
float fixedy = 5.03f;
public GameObject enemy;
public Movement player;
void spawn()
{
float x = Random.Range(minx, maxx);
Vector2 spawnpos = new Vector2(x, fixedy);
GameObject enemy_instance = Instantiate(enemy, spawnpos, Quaternion.identity);
}

public void Update()
{
    player.UpdateScore();
}
private void OnCollisionEnter2D(Collision2D col)
{
    if (col.gameObject.CompareTag("floor"))
    {
        spawn();
        Destroy(enemy);
        player.score_num++;
        player.UpdateScore();
    }
    if (col.gameObject.CompareTag("Player"))
    {
        player.score_num = 0;
        player.UpdateScore();
    }
}

}

Player function update score part:public void UpdateScore()
{
score_text.text = "Score: " + score_num.ToString();
}

edgy sinew
edgy sinew
#

!code

radiant voidBOT
edgy sinew
timber tide
#

I dont really use realtime IKs. I usually just bake my animations from blender

#

I'd assume you'd need to do a lot of clamping if values are exceeding what you're expecting

#

I'll get back to you when I finally get time to do the procedural spider animations I've been holding out on

edgy sinew
timber tide
#

some dampening then?

edgy sinew
#

So far I've been avoiding like, controlling the weapon's position directly and just using some Two-Bone constraints to slap the hands on.

edgy sinew
frosty yarrow
timber tide
#

Similar to what cinemachine does to prevent the camera from sperging out when lerping

#

like you don't want the camera to shake like crazy when you're driving a vehicle, ect

edgy sinew
frosty yarrow
edgy sinew
#

Probably just controlling the weapon's transform directly is the easiest solution. And simple Two-Bone IK for both hands of character

edgy sinew
#

If you add the score variable in an OnGUI, it shows the correct score there?

#
        GUI.Label(new Rect(10, 10, 100, 20), "The score is ", score);
}```
frosty yarrow
edgy sinew
#

I see, so that shows the score fine. So we can conclude the UI is not properly connected to the variable then.

scenic lotus
#

Hello

frosty yarrow
scenic lotus
#

I am new to game development in unity, where do i start?

frosty yarrow
scenic lotus
timber tide
#

from the very bottoms of c#?

scenic lotus
timber tide
#
frosty yarrow
edgy sinew
#

C# is not really gonna get in your way, it's a pretty modern language & configured to be able to do all the cool stuff required

timber tide
#

Do everything up to classes (including classes)

scenic lotus
#

I can't tell the difference yet my bad

edgy sinew
#

I recommend you determine what kinda game you wanna build and start watching YouTube (Unity 6 videos only, avoid low view channels)

timber tide
#

that's the 'you probably want to know that otherwise unity will confuse the heck out of you' development course

scenic lotus
edgy sinew
#

In any game engine you move an object, rotate it, attach stuff to it, assign some "runtime values" to it like Health or Mana points

sour fulcrum
scenic lotus
timber tide
#

You can do a lot with the editor tools, but this isn't like Unreal where you can get by with visual scripting

#

you'll be doing a lot of coding

scenic lotus
edgy sinew
#

Always try to use the best method up front rather than "hack together" a solution that "just works"

sour fulcrum
edgy sinew
#

For example

scenic lotus
sour fulcrum
#

Fail fast and fail often, doing it the bad way first is the fastest way to prove the concept and figure out if this is the kinda thing you want

edgy sinew
#

Ohh yeah liek that? yeah of course fail fast

sour fulcrum
#

If your new doing the jank way fast also helps in learning stuff initially and coming to the conclusions that would justify doing the better ways

edgy sinew
#

As long as you fully wipe the 'janky new code' once you've proven that it'll work, and then re-write it using proper concepts

#

done that a hundred times

sour fulcrum
#

Plus most games have a ton of permanent "temporary" solutions šŸ˜›

scenic lotus
#

There is also the official unity build with code course

#

Idk if that's right

frosty yarrow
edgy sinew
frosty yarrow
edgy sinew
frosty yarrow
edgy sinew
#

Does everything else work - spawn, Destroy, etc?

frosty yarrow
edgy sinew
#

What does the score_num look like, what does the .UpdateScore look like?

frosty yarrow
frosty yarrow
edgy sinew
#

when you do player.UpdateScore()

frosty yarrow
#

yeah that is what i did

edgy sinew
#

In other words, trying to verify that the enemy MonoBehaviour is successfully calling the player.UpdateScore()

#

I see. Well, it sounds like witchcraft then! I'm sure something is off somewhere along the line.
There's no way you call a function and then nothing happens šŸ¤·ā€ā™‚ļø

#

Isn't it a bit strange to be doing player.UpdateScore() every frame in Update() - and then even more in OnCollisionEnter2D?

frosty yarrow
sour fulcrum
#

where is the textmeshprougui in the scene view

#

like is it on the screen

sour fulcrum
#

can you show that

frosty yarrow
ashen sorrel
#

uhh help i have made the unknown

ionic sorrel
#

I've been trying over and over to figure out how to work this out and it still hasn't been working.

#

I've been trying to use different methods to do this since those that tried explaining it to me didn't work either.

#

No matter what I do... The player is still able to jump midair FriskCry

ionic sorrel
frosty yarrow
frosty yarrow
frosty yarrow
ionic sorrel
frosty yarrow
ionic sorrel
frosty yarrow
ionic sorrel
#

In the screenshot it doesn't show... But it says "possible mistaken empty statement"...

#

At the bottom of the screen.

frosty yarrow
frosty yarrow
ionic sorrel
frosty yarrow
frosty yarrow
frosty yarrow
ionic sorrel
#

Alright hang on Imma get this.

#

Alright, I'm installing VS.

frosty yarrow
# ionic sorrel What? There's a different VS? :O

vs code has all of the langs but in c languages including c, c++, and c# is so hard to use and setup and doesn't support everything you will need but vs is more heavier and support all c triangle langs and to setup just choos the language and press download and that it and you can do any thing with it like c# program

frosty yarrow
ionic sorrel
frosty yarrow
frosty yarrow
# ionic sorrel I see :O

i just want to say unity is still hard and sometimes you will hate your life with it like me 1 hour ago because a problem especially in newest version because the neww input system doen't match the tutorial and you will need to change and do and do stuff but you will be able to make codes without even knowing

ionic sorrel
frosty yarrow
ionic sorrel
#

So... This C# package in the modifier... Is that the Unity one? Or is it a different one?

teal viper
#

!ide

radiant voidBOT
frosty yarrow
teal viper
#

Though, it does look configured. Why is there no error therešŸ¤”

frosty yarrow
ionic sorrel
#

I decided to rewrite the code as well.

frosty yarrow
frosty yarrow
ionic sorrel
frosty yarrow
wicked cairn
spring snow
#

what did you rewrite though

ionic sorrel
ionic sorrel
frosty yarrow
spring snow
#

there isn't any code though other than the built in script

ionic sorrel
real thunder
#

So, shooting, tracers, bullets...
I am shooting projectiles, from a gun, and a gun using smaller FoV than anything else
The obvious issue is that projectiles spawn where real gun is, I fixed that by just manually making starting point deeper but then I found a post saying code like:

shooting_pos = main_fov_cam.ViewportToWorldPoint(weapon_fov_cam.WorldToViewportPoint(barrel_pos));

would work and it does seem to work, however two issues arise
first is that if a gun is inside a wall projectile fly backwards, what would be a common fix?
second is that it needs a camera and I don't have a camera stack I use URP render feature, is there a formula or something which just use fov instead of a whole camera?

ionic sorrel
# spring snow what

Well idk. I had errors when I reopened the project. I don't mind though, its not like I'm on a time limit or anything Shrug

frosty yarrow
# ionic sorrel Is that right? :O

the code is write but you can just give the floor a tag and check if the play on the floor if make a var called grounded make it true if not on ther floor make it fals and mkae when the player jump and grounded == true then add force

real thunder
#

on second thought

shooting_pos = main_fov_cam.ViewportToWorldPoint(weapon_fov_cam.WorldToViewportPoint(barrel_pos));

might overstretch it on Z axis but I am not sure how does fov work

ionic sorrel
spring snow
#

rude

#

šŸ˜”

frosty yarrow
spring snow
frosty yarrow
spring snow
#

it's not worth it

spring snow
frosty yarrow
spring snow
#

dont

frosty yarrow
spring snow
ionic sorrel
#

Well that was random FriskHaha

#

Thank you guys for helping me at least.

frosty yarrow
real thunder
#

oh, it seems like to grasp those concepts I would need to get into projection matrixes which I don't want to

#

I feel like I am missing something

spring snow
real thunder
#

doesnt look very hard but like
there gotta be an easier solution somewhere! right?

#

because it feels like I am doing the most basic thing ever

#

yet somehow every time I try to do most basic things ever I usually realize that somehow, somehow doing it right is very hard

azure forge
#

i was following a tutorial on youtube for adding sliding to an fps game but ended up with a null reference exception. i did a bit of research and found out that it's a very common error and found a guide to fixing these errors. im very inexperienced with code though and im not sure how to re write the code to find the null object.

azure forge
#

unless that isn't how to assign it

slender nymph
radiant voidBOT
slender nymph
#

also no, that is not an assignment, that is a declaration

rich adder
real thunder
#

find the null object that sounds kinda funny
anyway, like, don't treat is as an abstract error, it just means that code tries to do something which is null so... figure out why the variable is null
it's either you forgot to assign it before use or it got destroyed on the way or unassigned

real thunder
#

tho destroying is unassigning under the hood I suppose....

slender nymph
#

it's not. it doesn't unassign, and destroyed objects don't throw a NullReferenceException, they throw a different exception altogether

real thunder
#

ah ok, do they do that only at Editor btw?

slender nymph
#

they don't even get unassigned in the editor, they just turn into a "Missing" object (assuming you are referring to what you see in the inspector) and that object is still literally the same object on the C# side, it's just that the object on the native side no longer exists

real thunder
#

I just got something like a suspicious memory in my head saying that on builds there is no such thing

rich adder
rich adder
#

if you checked Player Log file you will get the same message as console in editor

slender nymph
#

there is no such thing as that "Missing" object you see in the inspector during builds because naturally that is drawn purely for the inspector. destroying an object does nothing at all to the variable that referenced that object, the variable will just now reference the destroyed object which is only "destroyed" on the native side because that's not a concept that C# has. you have to manually set it to null if you want it to be null.
This is actually precisely why the null conditional operators and pure null checks don't work properly for unity objects

rich adder
#

its like trying to look for the same object at specific "area" but no longer finds it so its missing, unlike null saying it was never there to begin with..assuming you don't set it to nothing yourself ofc with = null

slender nymph
#

eh, you can technically still perform some operations on destroyed objects, provided anything you are doing never touches the native side so it's more like finding a broken object there rather than a missing one

rich adder
azure forge
rich adder
real thunder
#

If I were you I would just use [SerializeField] and put it right in the inspector

rich adder
#

ideally

azure forge
rich adder
#

still, lookup what assignment is / does

#

configured editor now tells you whats wrong with your start

#

hover the green underline

real thunder
#

not capital letter start, rip

rich adder
#

void Awake(){ start(); } šŸ˜†

azure forge
rich adder
#

rb is probably one the only acceptable variable you can abbreviate like that

real thunder
#

I got plenty of those

rich adder
#

using abbreviations esp 2 letter variables is pretty smelly

real thunder
#

"parsys"

rich adder
#

your future self will hate you for it

real thunder
#

is rndrr acceptable in your book

rich adder
#

if its a serious q, no cause I can't read it and know exactly wat it is

real thunder
#

a renderer of course

rich adder
#

thats a pretty gross abbreviation lol

real thunder
#

no idea where did I pick this up but I use "no-vovel-case" time to time

#

well, probably as long as I am not sharing my code it's fine

rich adder
#

not a fan, but its your code do as you wish.. as long as you know what it is and ain't workin with a team having to explain to everyone what the hell it is

real thunder
#

I have indeed hated myself for vague abbreviations

rich adder
#

annoyingly unity still has legacy code where renderer was built in property

real thunder
#

yeah

rich adder
#

same with light

real thunder
#

let there be lght

azure forge
rich adder
#

variable names should be descriptive as possible

#

if its PlayerMovement component then playerMovement you know exactly what that variable is for instead of pm ? is this a clock ? time? peeMan?

real thunder
#

speaking of code conventions I realized I hate CamelCase and like snake_case
using latter in Unity feels... illegal

rich adder
#

pretty common in c++

real thunder
#

since it exists I am pretty sure it's pretty common at some spaces

rich adder
#

unity engine has the most mixed up conventions ever

real thunder
#

My code have the most mixed up conventions ever

rich adder
#

camel case properties, c++ conventions for fields like m_ prefix etc

#

in the end it doesn't matter, as long as you can read it and works for you . They are suggestive to keep consitency across devs, not really hard set rules

real thunder
#

hey m_! exists, good to know that I am not crazy
I just randomly started to name fields I am not meant to use outside of properties like _field

#

by randomly I mean always but I invented it for myself

rich adder
#

C# conventions says you prefix private fields with _ but barely see that anymore, i myself don't like code looks nasty with _ everywhere.. does help find fields in IDE but just looks messy

#

not even C# docs does it anymore

real thunder
#

those _fields just hanging near properties in code and never used anywhere(unless weird stuff) so

#

doing it ever since I accidentally used a field over a property

rich adder
#

to me, if its Pascal its either a property or a method, plus naming convention (they are pretty much similar anyway)
naming convention also help distinguish them anyway from classes.. eg ActionsDescription vs Object names
(methods are mostly verbs)

real thunder
#

since I started using snake_case for variables it made it so easy to distinguish CamelCase methods and long_ass_self_explanatory_variables

rich adder
#

yup as long as the variable name is descriptive, the casing is less important how you do it

real thunder
#

or am I

#

this example is so vague

rich adder
#

oh jeez I never noticed this part..

Use meaningful names. Don’t abbreviate (unless it’s math): Your variable names should reveal their intent. Choose names that are easy to pronounce and search for – not just for your colleagues but also to provide extra context to the code for when using AI tools, as this can contribute to more accurate code generation and suggestions
šŸ™„

real thunder
#

can we promptinject something by posting variables with prompts as their names on github

#

anyway if a class using alot of other class's stuff using won't help if it's an exemplar right?

#

I know it's not a nice practice to begin with, but...

#

at least I limit myself with just one layer of doing that

rich adder
#

you talking about using directives?

real thunder
#

I suppose

rich adder
#

I mean if you fully qualify every class, your dependency does not change..

#

its just convenience for you

real thunder
#

I don't really care about dependencies (and somehow getting away with it)

#

but if I use another class's variable instead of calling it's method it's... fine
however if I use another class's linked class's variable it's not fine

#

I feel like I am mixing up classes and other types of fields here but like u got the idea

real thunder
#

anyone can save me much time describing how does WorldToViewportPoint works internally?

real thunder
#

someone else's code work but it's always sliiightly off, good enough I guess
nvm it's not off it was on me

public static Vector3 Test(Vector3 aCamPos, Quaternion aCamRot, float aFov, float aAspect, Vector3 aPos)
    {
        Vector3 p = Quaternion.Inverse(aCamRot) * (aPos - aCamPos);

        float f = 1f / Mathf.Tan(aFov * Mathf.Deg2Rad * 0.5f);
        f /= p.z;
        p.x *= f / aAspect;
        p.y *= f;

        p.x = p.x * 0.5f + 0.5f;
        p.y = p.y * 0.5f + 0.5f;
        
        return p;
    }
#

Is this really necessary for proper shooting using 1 camera an different fovs? Sigh, it seems so

wicked cairn
#

It depends on your other setup, can’t judge by just that function

light cave
#

please someone tell me what the hell am i supposed to do

#

im a patient man and thought unity finishes it

#

but it compiles the empty file FOR 18 MIN

#

and i pressed cancel hoping it does something but it didnt

#

and i know if i use task manager i will lose mah work

twin pivot
#

Yea every time that happens i just kill it with task manager and hate myself for not saving

light cave
#

._.

#

gimme a moment

#

can i kill the compilation part itself?

twin pivot
#

Never tried that actually

light cave
#

FAHHHHHHHHHHHh

#

i killed the whole

#

damn it unity

#

actually

#

it saved everything

gloomy heart
#

You can get help from The Multiplayer Category, there are various links and resources

slate badge
#

Let's get replying to our NPCs with dialogue options and branches these responses into conversations! So when our NPC asks a question, a Dialogue Box will open with response options for us to reply with!
Previous NPC Video: https://youtu.be/eSH9mzcMRqw
We'll be building from our previous NPC tutorial - and tidying up a bit of that code by addin...

ā–¶ Play video
#

I recently followed this youtube tutorial to add dialogue choices in my game but, I don't know how to make the wrong choice go back to the question.

#

For example, if a person chooses "no", how do i make the dialogue box say smth lk "let me try again" and then asks the question again

#

Thank you if u can help!

wintry quarry
#

In general you would just make that dialogue option point to a path in the dialogue graph that loops back to the decision point again

#

If this tutorial isn't modelling dialogue as a graph, then it's not a very good framework

#

Rough sketch of the dialogue graph

glass summit
#

hey for my VN project, i want to make it so that the person that is speaking should be set active on screen, but the other characters should not. however when a scene starts, there is a fading animation for all the characters, from visible to invisible. so when i try to set certain characters active for specific moments, the fading animation always plays while the text is moving. How can i modify my code so it doesn't animate when they're speaking, but only when the scene starts?

#

this is my code

sour fulcrum
#

did you make this code

glass summit
#

it might be repetitive since i'm new to programming and idk a better way to make loops while having the speak texts different

naive pawn
#

well, note the parts that are different. a loop can count up or go through a list, so you can detect a change in each iteration. that can be what makes each iteration different

queen adder
#

yo

glass summit
#

i kinda need help with what i mentioned above

naive pawn
#

fair, but you should keep it in mind

#

removing unnecessary repetition makes it easy to tweak or fix, and you remove the risk of "X1 works but X2 doesn't because they're slightly different"

naive pawn
#

is it an Animator that does that when the gameobject is activated?

glass summit
naive pawn
#

then either
a) don't deactivate and reactivate your gameobjects, you'd do something like enabling/disabling the spriterenderer or set an animator trigger to show/hide the sprite
b) don't have it fade on active/inactive, use triggers to control the fade

or both

glass summit
#

i want to try the second option since that sounds easy enough, but not sure how to do it yet

naive pawn
#

do you know what animator parameters are

glass summit
#

I only know what animator controllers are

naive pawn
#

try googling those

spare saddle
#

Do you follow a course or just search up whatever you currently want to code in your projects? Is it worth taking courses?

twin pivot
#

!learn

radiant voidBOT
gloomy heart
dusty sail
#

so i got a question gng why does my object go to the canvas corner when i am trying to move it??

    {
        pt=transform.parent;
        transform.SetParent(transform.root);
        transform.SetAsLastSibling();
    }
    public void OnDrag(PointerEventData eData)
    {
        transform.position=SharedData.MousePosition;
    }
    public void OnEndDrag(PointerEventData eData)
    {
       transform.SetParent(pt);
    }

snippet of the actual code (learning form youtube)

wintry quarry
dusty sail
#

yep ui in canvas

#

inventory system gng

wintry quarry
#

You're doing this:
transform.position=SharedData.MousePosition;

Mouse position is generally in screen space.
The Transform.position for a UI element is going to be in a different coordinate space. Exactly how that relates to screen space depends on what your Canvas and CanvasScaler settings are

#

also I would highly recommend getting the position from the PointerEventData directly

#

e.g. eData.position

#

rather from elsewhere

dusty sail
#

how to use onDrop to add to someother slot hmm?

#

cuz the pointer is not dropping if i do that

#

is there another way to add to a slot?

spring snow
dusty sail
light cave
#

i have issue

#

sound plays twice when colliding

#
void OnCollisionEnter2D(Collision2D collision)
{

    float collisionForce = collision.relativeVelocity.magnitude;
    float collisionVolume = collisionForce * 0.1f;
    collisionAudioSource.volume = collisionVolume;
    collisionAudioSource.pitch = Random.Range(0.95f, 1.05f);
    if(!collisionAudioSource.isPlaying)
        collisionAudioSource.Play();

}
light cave
#

Car object has rigidbody and boxcollider2d

light cave
polar acorn
light cave
#

i don't understand

#

i use rigidbody for movement

polar acorn
#

Are there multiple instances of this script between the two objects involved in the collision?

light cave
#

i only use this script once

polar acorn
#

Then it's probably colliding with two things. Try logging collision.transform.name to see what you're colliding with

light cave
#

there is one collision

#

yet two sound playing

polar acorn
#

How do you know there is one collision?

light cave
#

nevermind

#

i actually put an echo in the audio mixer

dusty sail
# wintry quarry e.g. `eData.position`

Nah i used this cursed thingy (which i came up on my own)transform.position=new

Vector3(SharedData.camera.WorldToScreenPoint(SharedData.MousePosition).x,SharedData.camera.WorldToScreenPoint(SharedData.MousePosition).y,transform.position.z);

and allowed raycast and added some canvas group thingy
(chatgpt helped me,i was hell bent on not using ai but sadly i gab in)

naive pawn
#

hey, at least you're doing it yourself

ionic sorrel
#

My grounding code works now! :D

naive pawn
#

that's.. cool and all, but.. did you just not process any of the advice about using parentheses

polar acorn
gloomy heart
frail hawk
ionic sorrel
frail hawk
#

so your player looks into the direction you move

ionic sorrel
ionic sorrel
polar acorn
#

Like, how did you get from point A to point B

#

This is a completely different sentence

naive pawn
ionic sorrel
polar acorn
#

There is literally only one line in the code you've shown that checks isGrounded at all

naive pawn
zenith cypress
# ionic sorrel Look I'm new to coding, so I have no idea what you're trying to tell me <:FriskH...

Instead of this back and forth nonsense. He means this:

// this has the IsGrounded check twice
if (Input.GetButtonDown("Jump") && IsGrounded || Input.GetKeyDown(KeyCode.W) && IsGrounded) {}

// that can just be this
if (isGrounded && (Input.GetButtonDown("Jump") || Input.GetKeyDown(KeyCode.W))) {}

// or this
if (isGrounded) {
  if (Input.GetButtonDown("Jump") || Input.GetKeyDown(KeyCode.W)) {}
}

// etc
frail hawk
naive pawn
naive pawn
ionic sorrel
naive pawn
#

do you understand operator precedence at this point

#

you really should

#

and you already do, just maybe not with that name

ionic sorrel
naive pawn
slender nymph
frail hawk
naive pawn
#

because it's archived

slim solar
#

Hey where can i ask about UI components like Input?

#

Would that be here or is there a more general unity area?

zenith cypress
slim solar
wintry quarry
slim solar
#

Sorry I meant toggle lol, not input

#

But great, just customized all my channels, didn't realize so many were hidden by default

pliant dome
#

What is the GetAxis == 0 equivalent to GetButton?

slender nymph
#

well what type does GetButton return?

proper compass
#

Can anyone with a high knowledge in Photon PUN, Playfab and C# help me? I am trying to make quite a hard script (at least for me) and i am not too sure how to do it.

slender nymph
#

don't crosspost, but also this question probably belongs in a thread #1390346827005431951 (which means you need to delete it from other channels when posting it there)

proper compass
slender nymph
#

and yet it's still networking related. did you know that network related code still belongs in the networking channel on account of it being networking?

proper compass
#

Its not just network related

slender nymph
#

that was not directed at you

ionic sorrel
#

@zenith cypress thank you again for telling me the thing earlier. Nodders

polar acorn
ionic sorrel
frigid swift
#

can somebody tell me what im doing wrong here?

slender nymph
#

!ide šŸ‘‡

radiant voidBOT
frigid swift
#

ill keep that in mind but may i get an actual explanation of what im doing wrong please

slender nymph
#

if you configure your IDE you'll have an easier time realizing what you did wrong. it is also a requirement to have a configured IDE to get help with your code here

frigid swift
#

okuyy,,

#

ok well how do i do that?

slender nymph
frigid swift
#

i see the links ur trying to send me but idk what specific things its trying to tell me to do thats the problem šŸ’”

#

i have it linked to unity and ive got the unity extension for vscode and everything

slender nymph
#

did you try reading the linked guide to find all of the steps you need to complete?

#

because the issue is that vs code is not linked to unity, at least not fully

frigid swift
#

i already have the visual studio package and i have it set as my external editor i dont know whats happening

slender nymph
#

okay and what about the other steps

frigid swift
#

is this the right page??

slender nymph
#

yes, try reading all of the steps on that page

frigid swift
#

ok. the problem is.

#

this IS all the steps on the page

slender nymph
#

and have you installed the "Unity for Visual Studio Code" extension from the Visual Studio Marketplace?

frigid swift
#

yes, i do

slender nymph
#

then pay attention to the errors in vs code

frigid swift
#

im trying to get some help seeing what to change based off of this error because i have no idea what ive done thats wrong

slender nymph
#

you need to get vs code configured first.

frigid swift
#

can i have a more in depth explanation of how to do that than being pointed towards something that clearly isnt helping me?

slender nymph
#

hey remember when i said "pay attention to the errors in vs code" and you completely ignored that?

frigid swift
#

theres no errors in here at all

slender nymph
#

if you see no errors at all including in the Output panel or whatever it's called (and no, i don't mean errors in the code right now, i am referring specifically to *within vs code) then you probably just need to restart your computer

frigid swift
#

i restarted my computer and opened vscode and this error popped up, could this be the problem?

slender nymph
#

yes, that is exactly the problem. make sure that the .net sdk is actually installed

frigid swift
#

ok yeah it works now lmao sorry for being snarky it was frustrating me abit

slender nymph
#

great, if vs code is now properly underlining your errors, you should retype that line you're having trouble with making sure to use the intellisense to help you

wide fable
#

I'm planning to make a RPG engine should i make the player a prefab?

slender nymph
#

not exactly a code question, but probably

frigid swift
#

can someone tell me why calling the audiosource component is making the variable not exsist

#

ok its just not exsisting at all even without calling it somebody help

rich adder
frigid swift
#

its greyed out and when i tried referencing it later in the script i was getting an error telling me it doesnt exsist

rich adder
#

!code

radiant voidBOT
rugged beacon
#

the field right there

frigid swift
#
using UnityEngine;
using UnityEngine.SceneManagement;

public class PlayerController : MonoBehaviour
{
    public float moveSpeed;
    private float horizontalInput;
    private float verticalInput;
    public bool isDead;
    private SpriteRenderer sprite;
    public Sprite Deathsprite;
     AudioSource playerAudio;
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        sprite = GetComponent<SpriteRenderer>();
        playerAudio = GetComponent<AudioSource>();
    }

    // Update is called once per frame
    void Update()
    {
        horizontalInput = Input.GetAxis("Horizontal");
        verticalInput = Input.GetAxis("Vertical");
       if(isDead == false)
        {
             transform.Translate(Vector2.right * moveSpeed * horizontalInput * Time.deltaTime);
        transform.Translate(Vector2.up * moveSpeed * verticalInput * Time.deltaTime);
        }
    }
    public void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Kill"))
        {
            Invoke("Die", 0f);
        }
    }
    void Die()
    {
        Debug.Log("works");
        sprite.sprite = Deathsprite;
        playerAudio
        isDead = true;
    }
}
rich adder
frigid swift
#

i deleted that on accident hold on

fallow ether
#

yo guys how do you save scenes? I had to remake a ton of shit when I clicked onto a new scene (despite saving the whole project a ton) and I really dont want a repeat experience

torn mango
#

how does one change color of the material?

rugged beacon
#

no you dont need to, default is private
the field does exist there

#

try .volume or smt

frigid swift
#

wjat

rugged beacon
#

your error

rich adder
frigid swift
#

what is .volume gonna do?

rugged beacon
#

to prove the field exist

frigid swift
torn mango
#

it says URP

rugged beacon
#

just use the audio variable like normal

rich adder
torn mango
#

when I change to standard my 3d asset turns transparent

rugged beacon
#

the error saying you are typing as a type not as a variable

fallow ether
# rich adder ctrl + s

no but like ive saved the whole project a ton and booted it back up and then wiped 3 days of unity work when I went to make a menu screen

torn mango
#

sprite lit default

fallow ether
#

ctl + s a ton

frigid swift
radiant voidBOT
rugged beacon
#

ignore the error, and just your variable normal

frigid swift
#

i cant playtest the game if theres an error

rich adder
#

mate you need to learn the basics of c#

rugged beacon
#

fr

frigid swift
#

i know kinda how the variables work im in a class for it rn

torn mango
#

why did my plane turn transparent

frigid swift
#

i have no idea why this isnt working

rich adder
fallow ether
#

aight

rich adder
fallow ether
#

i have been able to close and boot up the project a ton without issue tho

rugged beacon
frigid swift
rugged beacon
#

it exist, read the error again, it saying the type doesnt exist

rich adder
rugged beacon
#

it even link to the field

frigid swift
#

im trying to do something like this tutorial

torn mango
rugged beacon
#

yeah and type out the rest man

torn mango
#

should I just use standard?

rich adder
rich adder
#

why dont you just make a default material, why did you change shader on it

frigid swift
#

oh.

#

im so fucking stupid

torn mango
#

I cant change the color of the default mat I created

rich adder
#

normally the color for that is changed through sprite renderer

torn mango
#

I see

rich adder
#

otherwise it has to be done through code using _Color in the method directly messing with shader

frigid swift
#

ok ignore squidward how do i move the layers on the ui

rich adder
#

hierarchy order. also not a coding question

frigid swift
#

sorry

fallow ether
#

yo me and a friend are about to check in a buncha work on the same project

#

is that gonna overwipe anything if we didnt do anything on the same scene

slender nymph
#

if you were not working on the same files then there will be no merge conflicts. also not a code question

fallow ether
#

oh right sweet

#

tyy

#

which channel can I ask questions like that in?

teal viper
fallow ether
#

thank you!

sour fulcrum
#

i've tried googling this but my brain is blanking please forgive me, how would i format an int to a string with two places? eg 7 -> 07 & 12 -> 12

#

I see a lot for decimal related stuff but i can't figure out how to do it out of decimal context

eternal needle
sour fulcrum
#

šŸ™

upbeat forum
#

As someone who is new to C# but has some basic understanding of coding concepts (variables, functions, loops, a bit a of classes and Inheritance) would you guys consider the coding learning path on unity learn worth going through?

keen dew
#

yes

fallow ether
#

definately

#

ive tried a bajilillion different ways, I just cant stop my first person player from being able to turn around and shoot itself beucase the object doesnt rotate with the camera

#

since its for a game jam ive sorta just resigned myself to the fact I just have to make levels all face only one direction and hope to god the player doesnt turn their camera

upbeat forum
fallow ether
#

currently this is the setup

#

very indicative of someones first ever 1st person cam whose also on time crunch

blazing kiln
#

hello! for an isometric tactics game where I'll need to do tile distance-based calculations, allow the player to click on a certain tile to move a character to, apply logic based on what tile a character is on etc. is an isometric tilemap more trouble than it's worth or is it appropriate? The alternative I was thinking of being just having a bunch of gameobjects with a quad mesh

fallow ether
#

only problem is got is the nozzel position aint following now

#

got it working:D

#

thanks!

wicked pulsar
blazing kiln
wicked pulsar
#

All Tilemap really does offer methods to modify and retrieve TileBase. It's a really simple collection class with minimal controls for positioning child objects.

upbeat forum
fallow ether
#

ay guys I dont use IEnumerators much so trying to figure out where I went wrong here

midnight plover
#

!code

radiant voidBOT
gloomy heart
fallow ether
#
using UnityEngine;

public class Cannibal Attack : MonoBehaviour
{
    [Header("test")]

    public GameObject turretBulletPrefab;

    public Transform nozzle;

    public float reloadTime = 0.6f;
    public bool reloading;

    public EnemyRadar radar;

    // Start is called before the first frame update
    void Start()
    {
        radar = GetComponent<EnemyRadar>();
    }

    // Update is called once per frame
    void Update()
    {
        if (radar.isActive && !reloading)
        {
            Debug.Log("Fire!");
            Instantiate(turretBulletPrefab, nozzle.position,
           nozzle.rotation);
            StartCoroutine("Reload");
        }
    }

    IEnumerator Reload()
    {
        reloading = true;
        yield return new WaitForSeconds(reloadTime);
        reloading = false;
    }
}
#

yee got it

#

lmk if ya perfer it in one of the sites

midnight plover
fallow ether
#

oo thanks yall

#

thats a IEnumerator thing right?

midnight plover
fallow ether
#

IEnumerator Reload() this thing, first time trying to use em

midnight plover
#

First of all, its not the best idea to start a coroutine from Update, but I still dont get your question. IENumerator is an IENumerator šŸ˜„ its a coroutine you start which can yield its execution

fallow ether
#

i have found the issue and I honestly deserve this

#

I tried reusing some code I knew already worked so that messed it up in a buncha fun unforseen ways

#

unity was like "nuh uh we doing this by hand again"

midnight plover
#

Glad you found the issue

fallow ether
#

tyy for the help:))

warped valve
#

I'm trying to make a retro resident evil style door system, the player should be able to go up to a door, press E, then the camera will switch, the door animation will play, then the camera should go back to the player camera. At the moment, nothing happens when you go up to the door for an unknown reason.
Here is the gate animation script:
https://paste.mod.gg/thvkchqyvfju/0
Here is the camera transition script:
https://paste.mod.gg/pyvmjkwmduxw/1

gloomy heart
#

Is the door collider set to trigger, and your player's tag is "Player"

warped valve
gloomy heart
warped valve
gloomy heart
#

Log it to console

warped valve
wintry quarry
#

You need to do more debugging

warped valve
wintry quarry
#

When you start the coroutine, and at various points within the coroutine

tiny island
#

hi , does someone know where i can find a document on how to change a sprite permantely even after the game is closed?

keen dew
#

The simplest way is to save a value to playerPrefs, and check if it's set at game start and set the sprite then

sour fulcrum
#

Ideally good to not use playerprefs for that kinda stuff tho

keen dew
#

meh, good enough for one-time use

#

not that good if there's lots of them

silk night
#

the knowledge about that can be easily transfered to saving and loading config files

little meteor
#

The new PT pacakge has a neat save system too that works across platforms and is very easy to use.

tiny island
#

rn i'm trying the PlayerPrefs thing as i only need to save a bool but it doesn't seems to work.

i get the "nuhuh" message when i launch the game but the gameobject isn't getting destroyed

#

am i doing something wrong?

keen dew
#

You're not doing anything with val

wintry quarry
#

yep, definitely doing something wrong

rough granite
#

Nvm i see it in Save()

wintry quarry
#

I mean the code just doesn't make any sense and the Saved variable is pointless, as written

rough granite
#

But this would mean that to load you must save in that same instance before hand

tiny island
#

sound about right , time to read again

rough granite
tiny island
#

tkx , i didn't notice the val not being used

the facepalm is real

wintry quarry
#

yeah but like

#

look at this

#

Saved is pointless here, and so is the ternary operator

#

it will always be true, so you will always be setting to 1

#

you can delete all of this except PlayerPrefs.SetInt("Bot_Sprite", 1);

tiny island
wintry quarry
#

it's not just deleting the : 0

tiny island
#

oh...mb

slim solar
#

Hey guys what's the proper way to load a map without blocking/freezing?
SceneManager.LoadScene("Main");
Freezes until the level loads

#

even if I put a black 'loading' screen on first, it's frozen

wintry quarry
#

!collab

radiant voidBOT
# wintry quarry !collab

:loudspeaker: Collaborating and Job Posting

We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• ** Collaboration & Jobs**

sudden hamlet
tiny island
raven smelt
#

I have a problem with this code. I don’t have much programming experience and I need help. The issue is that the animations won’t change, not even when using an integer variable. I already asked ChatGPT before, but it didn’t solve the problem. Can someone help me, if possible?

naive pawn
raven smelt
# raven smelt I have a problem with this code. I don’t have much programming experience and I ...

And here is the rest of the code. About 70% of it was generated by the AI. I may have made a mistake somewhere in the code.
I can’t upload the code directly because I don’t have Discord Nitro, but I shared a Google Docs link. I hope that’s not a problem.

https://docs.google.com/document/d/1Qj3Zfvt_7qFFMxXVhSvpAa4Z7wEsS-t_LQvuZXtIsLA/edit?usp=sharing

gloomy heart
naive pawn
#

that.. definitely is a problem

#

!code

radiant voidBOT
naive pawn
#

share it properly

raven smelt
naive pawn
#

and.. yeah, not many people will want to help with AI bs code

#

it's such a pain to work with because you, as the asker, have no idea what's going on

#

you should ditch the AI and learn for yourself

sour fulcrum
#

Especially when generally the goal when helping is to teach the person not just the solution but ideally how they could have come to that conclusion themselves

#

fixing ai code doesn’t help that

raven smelt
# naive pawn and.. yeah, not many people will want to help with AI bs code

I understand what you mean. I don’t want the AI to do all the work for me; I’m using it as guidance while I learn programming. I’m learning gradually, but I’m stuck with the animation system. I’m doing it on my own, but as I mentioned, I’m not an expert in Unity programming.

peak flame
#

Guys I'm new to C#. What should I start with as practice? Also would it be possible for me to make a full game by 2026 despite only now starting to learn script In Unity

naive pawn
#

but many marketable games take multiple years to complete even for people with a ton of experience

raven smelt
naive pawn
naive pawn
raven smelt
naive pawn
#

...are you actually gonna answer that

#

or are you unable because AI has done that and you don't know how anything is supposed to link up

rough granite
naive pawn
#

they aren't really designed for it

raven smelt
naive pawn
#

why would that change an animation

raven smelt
#

I don't know if the AI ​​passed it to me incorrectly.

naive pawn
#

are you using layers in place of animation states?

rough granite
raven smelt
# naive pawn why would that change an animation

The problem is that I have several animations, and when the character is close to an enemy or aiming at them, the animation should switch from 2D to a 4-direction 2D animation.
When the character aims or locks onto an enemy, the animations don’t blend or combine correctly, and I don’t know why.

naive pawn
queen adder
#

Is there a way to customize what the template script looks like when one is created and opened for the first time?

#

Ie instead of the start and update functions with two comments on top, I could put whatever I'd prefer myself

naive pawn
#

yes, you can edit the templates used

#

i don't remember where exactly though

gloomy heart
#

i also want that

queen adder
#

C:\Program Files\Unity\Editor\Data\Resources\ScriptTemplates

#

Figured it out

#

They're all in there

#

The path might look a little different for some of you, but you'll find your way

gloomy heart
#

found them

swift crag
#

unity still needs to throw out the old scene's objects and instantiate the new ones

#

and there's generally a garbage collector pause in there, too

slim solar
#

Yeah for sure, it's just so the load screen can have a bit of animation šŸ˜›

swift crag
#

I play a very brief transition animation, let the scene activate, and then reverse the animation

#

when I use the Recorder, the giant hitch goes away, and it looks really nice

#

shame that it's not so good in practice

astral sentinel
#

is this course good for learning unity? also is there any course you guys suggest.

midnight tree
charred monolith
#

I got a question, how i can get the components from another gameobject.
so like i got a script that gets the component but i need component from another gameobject.
that means GetComponent doesnt work.
in my case, im case i instantiate the Prefab and i ALSO get the component but the component is not on the gameobject.
its on the child. Also it has to be on child due to my other scripts.
Here is my single line of code where i need help at:
https://paste.mod.gg/iuzseitxvefy/0

charred monolith
#

btw please do not hate on me what i did wrong

charred monolith
polar acorn
charred monolith
frail hawk
#

do you want to call the GetComponent on a instantiated prefab?

polar acorn
raven smelt
charred monolith
charred monolith
polar acorn
charred monolith
#

but thanks for helping me anyway

#

im so glad that theres a getcomponentinchildren function

frail hawk
#

something is legacy in your code (veraltet) i can read

polar acorn
charred monolith
charred monolith
polar acorn
nocturne kayak
#

Hello guys why is the cooldownUntilNextPress having + 5 each time i press the button when i set CooldownTime to 1 ? script :
`public float CooldownTime = 1f ;
float cooldownUntilNextPress = 0f ;
private void Awake()
{
m_click = InputSystem.actions.FindAction("MouseClick");
m_item_1 = InputActions.FindActionMap("Player").FindAction("Item1");

}
void Update()
{
   m_clickAmt = m_click.ReadValue<float>();


    print(Time.time);
    print(cooldownUntilNextPress);
   
    //TKT SCR
    if (m_item_1.WasPressedThisFrame() && cooldownUntilNextPress < Time.time)
    {
  
        print($"Has been pressed : "+ isItemHold);
        isItemHold = !isItemHold;
        cooldownUntilNextPress = Time.time + CooldownTime; 

    }
}

}`

zenith cypress
#

Is the inspector value set to 5

nocturne kayak
#

oh i didnt think of that let me check

frail hawk
#

cooldownUntilNextPress < Time.time this would make more sense if it was Time.time > cooldownUnitlNextPress

nocturne kayak
nocturne kayak
#

thanks guys

zenith cypress
frail hawk
#

and when resetted

nocturne kayak
frail hawk
#

as soon as time is higher than your cooldown it shoudl allow your press

nocturne kayak
#

oh Yes

#

Maybe I should stop for today, I'm just messing around lol

undone wolf
frail hawk
#

there are a few ways to solve this however.

undone wolf
# frail hawk disable anti aliasing

already disabled for me unfortunately, i did only hook up my camera to my player as a child for a quick'n'easy follow. think that's the problem?

frail hawk
#

no, i don“t think that is the problem

#

@undone wolf this should solve the problem.

undone wolf
supple phoenix
#

whats the best way to save informations between scenes?
should i just add to thing that i want to save:
private void Awake()
{
if (instance == null)
{
instance = this;
DontDestroyOnLoad(gameObject);
}
else Destroy(gameObject);
}

or should i make GameData script that saves information that i need in variables then it loads everything at the start of the scenes.

or maybe both?

wintry quarry
#

it depends

frail hawk
#

many ways, it depends on the data you want to save

wintry quarry
#

Jsut saying "DDOL Singleton" would suffice, you don't need to share the code

supple phoenix
#

yhym ty yall for help.

north walrus
#

When should I consider ServiceLocator pattern for wiring system in a game compared to singleton managers?

short gust
#

for 3D objects/scenes: at runtime, does toggle on and off isKinematic and Colliders when I need/don't need to use physics per object positively affects performance in general or it will introduce some overhead with jumping in and out of simulation (I don't know if it's even a thing, lol)?

#

oh, I forgot about rigidbody's Sleep/WakeUp thing, so my question is kinda stupid, heh

eternal needle
#

imo its a design issue if you have so many rbs that your game has performance issues. If an object just doesn't need a RB from the start, that's different

timber tide
thorn ginkgo
#

I have a prefab that I can see when looking at just the prefab. However, I do not see it when I put it in a parent component--that is itself in a canvas.

#

Does anyone have any tips to resolve this? Please note I just want the inspector to show the prefab. I am still working on the game portion

timber tide
#

Your hierarchy on the left there is disabled

naive pawn
naive pawn
#

it kinda already is

#

it's just not showing up because the object is inactive

#

probably due to a parent being inactive, considering the large swath of inactive gameobjects visible in the hierarchy (which i think mao was trying to point out)

spare saddle
#

Does anyone know what Im doing wrong here? Why the if statement is having red underline? I'm trying to make a script for my weapon model to make a basic weapon bob animation if the movement buttons are pressed (in this case I'm trying to make "w" which is foward.

thorn ginkgo
#

ah, I copy-pasted from a deactivated gameobject to make the root element

slender nymph
#

KeyCode is an enum, not a method

thorn ginkgo
#

that checkbox did the trick. Thank you

spare saddle
#

Yeah I'm still learning what enums are

naive pawn
#

the error message there should tell you what's wrong

#

hint: ||( needs to be paired with )||

spare saddle
#

Whoops. Easy to forget

wintry quarry
# spare saddle This better?

after you've been programming for a while unbalanced parentheses like this will look unnatural and wrong to you

rough granite
rough granite
radiant voidBOT
rough granite
#

Might be wrong though

naive pawn
#

errors are showing up as they should

rough granite
naive pawn
#

you try it out

#

(no, that's generally not how syntax errors are analyzed.)

rough granite
#

hmm seems so mb

naive pawn
#

the error message should give you a hint as to how they're analyzed

tranquil forge
#

anyone used unitask?
whats the different between the .switchToThreadPool and the .runOnThreadPool?
and what is this .create i cant find it mentioned anywhere else

wintry quarry
naive pawn
tranquil forge
#

same function just different style?

wintry quarry
rough granite
tranquil forge
wintry quarry
tranquil forge
#

is there more to this readme on github? i ctrl f the unitask.create thats the only place it mentioned

wintry quarry
#

IDK what it is

tranquil forge
#

is there another doc ?

grand snow
#

it is annoying that they dont document stuff more than the readme

tranquil forge
#

ah so this but return then, but why is it recommended to use this over .runonpool?

grand snow
#

Its that you should make sure you actually need to execute code on a different thread with those or not

#

you could use Create() and await another function to "move" to an alternate thread too

frigid swift
#

how do i even call this???

teal viper
frigid swift
#

im trying to change the text through the code

teal viper
#

text should be the right field property name if I remember correctly. You can confirm in the docs.

teal viper
#

!ide

radiant voidBOT
frigid swift
#

i have mine configured, im recieving an error in unity though

slender nymph
teal viper
frigid swift
#

let me send my code hold on

teal viper
#

!code

radiant voidBOT
frigid swift
#
using TMPro;
using UnityEngine;

public class NextDialogue : MonoBehaviour
{
    private int textNumber;
    public TextMeshProUGUI text;
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        textNumber = 1;
        text = GetComponent<TextMeshProUGUI>();
    }

    // Update is called once per frame
    void Update()
    {
        if(textNumber == 2)
        {
            text.text = "test";
        }
    }
    public void NewDialogue()
    {
        textNumber += 1;
    }
}
#

im trying to get a button to increment up the integer and change the text

#

i have the TextMeshProUGUI variable assigned to the text i wanna change

teal viper
frigid swift
#

it highlighted the canvas where the script is located

slender nymph
#

that object likely has this component attached to it when it shouldn't be

frigid swift
#

should i try attatching it to the textmesh instead?

slender nymph
#

the component uses GetComponent to get the TMP Text object, GetComponent is being called on the same object, if the Canvas does not have the TMP Text object on it then GetComponent will return null. So you need to either remove the GetComponent line and drag the reference into the slot in the inspector, or remove the component from the canvas and put it on the TMP object

frigid swift
#

okay thanks

#

OKAY IT WORKED thank you vro ā¤ļø

fallow ether
#

yo this might be the wrong channel but does anyone know a good tutorial for coding an npc that runs away from the player? like in a hunting game context or something

#

not having much luck online

placid jewel
fallow ether
#

oo ok thanks!

ashen sorrel
#

g'day yall i have sprite sheet of my player in diffrent positons how do I split it when I need to use the diffrent directions

slender nymph
#

not a code question. but use the sprite editor

ashen sorrel
#

no no

#

i need to code it so If i need it it auto splits

#

wait wait

slender nymph
#

what is that even supposed to mean

ashen sorrel
#

i need to use 1 of them

slender nymph
#

you can drag individual sprites into individual slots in the inspector. which means you'll need either a separate variable for each or an array.
or just use animations and animation parameters

ashen sorrel
#

im stupid

ashen sorrel
slender nymph
#

filter mode and/or compression on the texture's import settings. also not a code question.

ashen sorrel
#

english please

#

also what other channel would I use then?

slender nymph
ashen sorrel
#

not there

slender nymph
ashen sorrel
#

in that find a channel its not there

#

it no say about help

slender nymph
#

read the information in the channel

ashen sorrel
#

i did sorry my reading is not good

slender nymph
#

have you considered looking at the import settings for your texture? you might find what you are looking for there

ashen sorrel
#

close but "dumber"

slender nymph
#

instead of playing this game where you pretend you know nothing at all and expect people to spoon feed you the answer, try actually asking clarifying questions about the parts you do not understand

ashen sorrel
#

i do not understand the import settings im sorry

slender nymph
#

but do so in the proper channel so someone interested in continuing this can help you because i'm done.

ashen sorrel
#

Ok

celest mesa
#

hi there I need help with scripting Im having a project and im just now working on coding and making a small game but when ever im ready to do script or code the C# Script doesn't show only create empty and when i click on that one it takes me to visual studios but it doesn't show me the pre set up if this makes sense

teal viper
celest mesa
teal viper
#

!ide

radiant voidBOT
teal viper
#

Go through the "installed manually" guide.

bronze fossil
#

Hiii

I was looking at optimizing my code
my game uses only one camera(main) and it is 2d game

is it recommanded that i put it as a static prop in GameConstants/GameManager
rather than calling Camera.main everytime in some scritps(most of the scripts only use Camera.main for one time so no need to store it there)

frail hawk
#

create a reference to the Camera

#

it is not a good idea to call Camera.main every frame.

bronze fossil
#

should i still put it as a static prop for all script to access?

frail hawk
#

i have no clue what you mean with static prop, can you show some of the code

#

are you using a singleton?

bronze fossil
frail hawk
#

yeah that is fine

bronze fossil
#

public static GameManager Instance { get; private set; }

public static Camera MainCamera;
void Awake()
{
    if (Instance == null)
    {
        Instance = this;
        DontDestroyOnLoad(gameObject);
    }
    else Destroy(gameObject);

MainCamera = Camera.main;
}

so if other script wanted to have Camera.main then they would

GameManager.MainCamera

bronze fossil
frail hawk
#

is your script called MainCamera?

bronze fossil
hot wadi
#

Camera is the component

frail hawk
#

ah ok at very top i see now. you had some empty lines. i think there is no need to make the Camera static. you will have to assign it via inspector because it is part of tha Instance.

hot wadi
#

There is always 1 main camera so I don’t see the point of static ref here

frail hawk
#
[SerializeField] Camera maincam;
bronze fossil
hot wadi
#

Camera.main already does the work

bronze fossil
bronze fossil
# hot wadi How costly? Never heard of that

from what response i got

`It is highly recommended to cache it, but the reason has changed over the years.

The Short Answer
Yes, put it in your GameManager. Even though Unity has optimized Camera.main in newer versions (2020+), caching it is still faster and, more importantly, safer for your code architecture.

The "Why" (History Lesson)
In Old Unity (Pre-2020): Camera.main was incredibly slow. Behind the scenes, it literally searched through every object in your scene to find the one tagged "MainCamera" every single time you typed it. Using it in Update() was a performance crime.

In New Unity (2020+): Unity now does a bit of internal caching. It is much faster, roughly the same speed as GetComponent<Camera>().`

frail hawk
#

it says caching but nothing with singleton

#

caching simply means to create a reference one time and then use that instead of calling Camera.main every frame

bronze fossil
#

hmm ye

#

ok then

hot wadi
#

If it’s a scene object, it’s better to serialize it. Static can get a bit confusing