#💻┃code-beginner

1 messages · Page 517 of 1

devout flume
#

Also, a memory free isn't dramatic here & there, but as mentioned, if you do that too often, it's just not properly optimized. The thing is that you have an alternative which is way more memory friendly & more efficient, if you want to go with the parsing method, that's up to you

teal viper
#

I'd like to see a game engine without a garbage collector or a similar system.

devout flume
#

But this probablt involves at least an O(n) time complexity, alongside other factors that consume unnecessarily

devout flume
#

It would be addressed to advanced programmers, or even studios

#

Which in terms mean they would need to charge a lot of money for it to be sustainable

teal viper
#

It's not as much about "knowing" how to manage memory. Some complex systems simply can't function without sort of a garbage collector.

timber tide
#

people actually destroy their objects?

devout flume
#

I agree, it would be great to have an option to fully manage memory

silk night
#

Biggest problem for unity is that GC isnt generational

night raptor
#

One nice thing about cargabe collector is that the workload can be divided between multiple frames which unitys garbage collector does so you don't need to worry that much about performance even if you dispose of large amount of data at once

languid spire
#

Even more important, the vast majority of programmers are totally incompetent and so systems like garbage collection are a requirement to protect their users from crappy code

sleek marten
#

I've got a few scenes that are identical except for the types of enemy waves that are spawned. I know I can have all this data be in one scene but I'm not sure what method to use. For this type of data loading, would that be done with scriptable objects?

languid spire
night raptor
#

relative to the amount of objects in the heap would sound reasonable though

red harbor
#

Hi everyone! I’m a beginner working with prefabs, and I’m running into some issues with maintaining references in my Unity project. I have a car prefab that I spawn at runtime, and it needs to be assigned to the camera, but the reference to the car is lost every time I spawn it. Right now, I’m using FindObjectWithTag in Update() to re-assign it to the camera, but I know this might not be the best approach. The car also has button references for touchscreen movement (forward and backward), and because it’s a prefab, these references in the inspector are empty. I know I could assign them with a script, but it seems like it could get overly complex. Is there a recommended way to handle these references efficiently without a large script? Thanks!

rich adder
#

whatever is in the scene already had reference to camera, when you spawn you pass the reference

night raptor
cosmic quail
zealous atlas
night raptor
red harbor
#

Let me explain like this, for example, there are ui buttons which i use to move the car forward ,backward , left and right. All these buttons are assigned to player movement script which is on the car. As i am making a multiplayer game, i need to make prefab of this car and spawn it when player starts the match. So i made a prefab of this car . And when the match starts and the car spawns, all the buttons which i assigned are going away, like its showing none in the inspector. I dont want them gone...

rich adder
#

. As i am making a multiplayer game
oh lord..sure hope you mean same screen multiplayer..

red harbor
#

Its online multiplayer

polar acorn
#

You should probably not start with that

rich adder
#

you should def not be making multiplayer lol

red harbor
#

I already made all the physics and stuff dude

swift sedge
rich adder
#

should prob know to even pas references at very least..

#

hey its your game. Just not something you will probably not finish but hey, best of luck

swift sedge
#

you are trying to go into the deep end without even knowing the fundamentals of C#

red harbor
#

I mean i already know how to do it but chat gpt says its inefficient

swift sedge
#

chat gpt notlikethis

timber tide
#

I lie on the internet in hopes that chatgpt copies that lie and spews it out to someone

red harbor
#

😨

swift sedge
polar acorn
sleek notch
#

Hi, can someone help me why I can't see the list in Inspecotr?

#

please ping afterwards

rich adder
hexed terrace
#

it's [SerializeField] , not [Serialize] - though it's not needed for public fields

wintry quarry
#

Only serializable types can be serialized.

#

Primitive data types (int, float, double, bool, string, etc.)
Enum types (32 bits or smaller)
Fixed-size buffers
Unity built-in types, for example, Vector2, Vector3, Rect, Matrix4x4, Color, AnimationCurve
Custom structs with the Serializable attribute
References to objects that derive from UnityEngine.Object
Custom classes with the Serializable attribute. (Refer to Serialization of custom classes).
An array of a field type mentioned above
A List<T> of a field type mentioned above

sleek notch
#

Okay thanks

timber tide
#

Ya also don't need to initialize it with new

swift sedge
#

in modern C# you can use a primary constructor and do List<Emails> everyEmail = []

slender nymph
wintry quarry
#

List<Emails> everyEmail = new(); works just fine

slender nymph
#

or in this case, no constructor call is needed as Mao pointed out since the list is serialized by unity so an instance is automatically created

timber tide
#

man I made so much fun at c# about the syntax of the full initialization, then the next week they released the version for the short version

#

was like 2015 or something? Surprised it took them that long

swift sedge
timber tide
#

of course if you wanted to downcast it you would have to type out the full syntax of it

languid spire
#

syntactic sugar, there are so many other, important, things that the devs could be concentrating their energies on

slender nymph
red harbor
#

Guys i got the multiplayer working with photon fusion. Everything is working well. But the car movement is not smooth. Its a bit jittery. Can anyone please tell me how to fix it. Thanks in advance

slender nymph
#

#archived-networking
also photon has its own server you can ask for help with their networking tools in
and networking is not for beginners. you will fail if you don't actually understand what you are doing

red harbor
#

I followed their guide to make the player movement smooth but it isn't working. Guess I'll have to post this on networking

slender nymph
#

you would be better off asking in the actual photon server. and post actual details

lofty sequoia
#

is there a way in code to do the equivalent of alt + clicking the bottom left corner?

molten dock
#

you know the long notes in rythm games where you have to hold down on it and the bar is erased as you hold

timber tide
#

wouldnt that be x anchor 0, y = 1

lofty sequoia
#

what's odd is when I click alt + bottom left, it doesn't change the anchor values

molten dock
#

is it bad that im doing it by having lots of tiny gameobjects destroy

steep rose
rich adder
slender nymph
#

this is not a code question. and don't crosspost

steep rose
#

if someone does know they will respond

#

there isnt a certain someone

slender nymph
#

you've already asked for help in #💻┃unity-talk . keep the question there. and delete it from here

rich adder
#

how you been on in 4 months if latest unity dropped oct 17?

ancient halo
#

beta my dude

rich adder
#

if it wasn't working since preview/ beta the issue is somewhere with your PC / config

ancient halo
#

i see it "could be" but i see no reason for it not working out of the box

#

i didn't do any weird configs or anything it's just a standard win11 install

#

sorry for posting twice it's just driving me crazy i can't create a hdrp project at all or add any library that uses com.unity.settings-manager

#

for 4 month or more now

molten dock
rich adder
molten dock
rich adder
#

why would be issue destroying

molten dock
#

thinking it may be laggy to destroy 200-500 ish objects in a short period

rich adder
#

are you just assuming that or you actually tested this

#

when you set to Destroy it doesn't even do it right away, it waits till the GC is coming to collect

swift sedge
#

DestroyImmediate is a solution, but not recommended

rich adder
#

thats meant for assets not instances

swift sedge
#

but in the docs, it has a second parameter called "allowDestroyAssets"

rich adder
#

idk I only used it in the Editor which from what i know , should only be used in that context

#

like destroying maybe TEMP objects created in Editor

#

idk what the bool is for tbh my assumption is was for that by default

cosmic dagger
#

hey, where'd the question go? i was reading . . .

polar acorn
#

🦆 'd most likely

#

Figured it out while waiting for an answer

short meadow
#

Unfortunately no, I was gonna reformat but here it is.

Hello. I'm trying to display a crosshair and item name when my raycast hits a 3D object. I'm using a UI Image and a TMP_Text. Pretty much everything I have that's relevant has been up in the video below.

The Bug: When I look at an interactable object for the first time and my HUD displays, there is a jitter or jump in the camera. It only happens the first time the TMP_Text is drawn on the HUD.

Note: Sometimes the jitter or jump is larger than other times. Sorry if the issue seems super obvious, please pardon my incompetence. Also, in the video I had no idea why it was happening but have since figured out it's related to making the TMP_Text visible for the first time.

Video: https://www.youtube.com/watch?v=YulfGxssvJ8
PlayerInteraction.cs: https://pastebin.com/gyeYX9eR
Interactable.cs: https://pastebin.com/aJYh3kgM

Info & what I've found:
If it matters my player's movement is done in FixedUpdate() while my input is handled in Update().
I tried changing the PlayerInteraction for CheckForInteractable() to FixedUpdate but that did nothing, so I reverted it back to Update().
It's specifically when the line 48 of the 'PlayerInteraction.cs' runs. Why drawing the TMP_Text for the first time is causing a stutter? I have no idea and I'm not sure where to continue this debugging process. I confirmed it doesn't do this by commenting this line out which seems to fix the problem. There may still be a tiny stutter without it, but if so it's nearly unnoticeable. Could just be placebo for me looking for a stutter.

cosmic dagger
sage mirage
#

Hello, guys! So, I would like to know if there is a method in Unity that loops a clip infinitely. What I mean is that I don't want the clip to reset at the end in the loop of the clip but to infinitely being played over and over? I don't mean that loop because that checkbox is resetting the clip at the end of it's duration.

still elm
#

When the player dies a scene should load with a username text promting user to input a name. but should also be able to press play or quit too. this menu should looks the same as the startmenu except the text input thing. Is it better to have two different scences for that or have a deactivated element in the startscene and use same scene for gameover scene but with a logic saying if <player has died in gamescence> activate this gameObject. Which is the best?

short meadow
halcyon dagger
#

Does anyone know what are the names of the CONTEXT menu elements for every component? Like rectTransform in this case.
If there is a full list somewhere it would be great tho, but for know I only need to know how is the inputMap assets from the inputManager package called.
[MenuItem("CONTEXT/RectTransform/Action", priority = 1)]

visual rune
#

!blender

eternal falconBOT
visual rune
#

!cs

eternal falconBOT
cosmic dagger
vast hamlet
#

Hello, I'm just now starting to use Unity to make my first ever game, and I was wondering if anyone here could show me how I could add a border to my 2D game? Currently, if I set the RigidBody 2D's Gravity Scale to anything over 0, the character just falls from the map. so I would like to add borders so that I can add gravity to my game.

rocky canyon
vast hamlet
rocky canyon
#

you would just arrange them to be at the bounds of what ur camera is seeing..

#

and so on..

vast hamlet
#

Ah, got it

#

Could somebody explain to me how exactly I should set the box collider where the character wouldn't "hang" onto it, but instead just step on it?

short meadow
#

np, it won't take too long . . .

rocky canyon
#

main character looks like its collider doesn't match its shape..

#

looks like it only has a collider on its head

vast hamlet
undone pier
#

is there a simple coroutine class with OnCompleted callback in unity?

#

i want to have a list of coroutines and maybe end them before they finish

cosmic dagger
rocky canyon
#

you could probably make a custom class to handle it

undone pier
#

ye just asking quickly

cosmic dagger
#

or pass in a callback, or check a bool variable that can change outside of the coroutine . . .

rocky canyon
#
    var myCoroutine = coroutineHandle.StartTrackedCoroutine(MyRoutine(), 
            onCompleted: () => Debug.Log("Routine Completed!"), 
            onCanceled: () => Debug.Log("Routine Canceled!"));```
undone pier
#

thanks both of u

rocky canyon
#

good luck.. would be a cool helper class to keep for later

rocky canyon
#

if those are both 2D colliders it shouldnt be doing what ur video shows it do

#

unless ur movement code is bad..

cosmic dagger
#

that's how i ended up creating a timer class with a bunch of actions, like: onCompleted, onCancelled, onSuspended, onResumed, onUpdated, onRestarted . . .

vast hamlet
#
using UnityEngine;

public class MainCharacter : MonoBehaviour
{
    public FixedJoystick joystick;
    public float moveSpeed;

    float hInput;
    void Start()
    {
        
    }

    void Update()
    {
        
    }


    void FixedUpdate()
    {
        hInput = joystick.Horizontal * moveSpeed;


        transform.Translate(hInput, 0, 0);
    }
}
#

This is my movement code (I haven't added vertical functionality as I'll be adding a jump button)[

rocky canyon
#
        public TrackedCoroutine(MonoBehaviour owner, IEnumerator routine, Action onCompleted, Action onCanceled)
        {
            this.owner = owner;
            this.routine = routine;
            this.onCompleted = onCompleted;
            this.onCanceled = onCanceled;
        }``` something like this eh?
rocky canyon
#

given enough transformation it can literally clip/ phase right thru ur collider

#

must use Rigidbody2D and accurate physics functions (for the best collision detection)

vast hamlet
#

Could you recommend me a guide for that?

rocky canyon
# vast hamlet Could you recommend me a guide for that?

This tutorial goes over all the different options for moving a player in Unity and the benefits and disadvantages of each. It also goes over the difference between Rigidbody vs Transform movements. If you want to take a deep dive on how to do movement in Unity than this is the video for you!

Patreon:
https://www.patreon.com/gameGLiTcHsupport

S...

▶ Play video
#

gloss over this.. should show u some new stuff that u can then search more about

vast hamlet
#

Sounds good, thank you very much for the help!

vast hamlet
#

I'll take a look at both and see what'd be easier to implement into my current code. Thank you very much! ❤️

hard lodge
#

I will be making a dev beginner server if anyone is interested, dm me

slender nymph
cosmic dagger
rocky canyon
#

i just figure if ur dealing with coroutines its best to go ahead and have a reference to the mono

rocky canyon
#

since the other guy brought it up i figure i might try to implement it today

cosmic dagger
glacial jackal
#

can someone teach me c# i beg😭

rocky canyon
#

the monobehaviour / coroutine relationship makes it pretty difficult in my eyes

#

i could build it... but do i completely understand it..

#

^ thats the dilemma

cosmic dagger
# rocky canyon i could build it... but do i completely understand it..

that's the truth. it's best to isolate/work on it in a separate project. then you won't have any other distractions. just make a simple coroutine that counts to 10 every second or display a log after a certain time. then you can mess with the calling onComplete to check that it finished, onCancelled if it was cancelled manually, etc . . .

#

break a feature down into task, and complete each step at a time . . .

rocky canyon
#

i'll give it a shot

#

learning experiene if anything

cosmic dagger
#

that's why i attempted to create my own pooling system, so i can understand how they work and to be able to add custom features. of course, this was before unity decided to make their own, but it's good practice . . .

rocky canyon
#

ya, imma try.. if anything its events, actions, callbacks

#

all that stuff that im a bit uneasy about

cosmic dagger
#

that's the part of practicing most people don't do. it's hard to learn something (a concept) if you don't attempt it yourself . . .

rocky canyon
#

my project directory shows absolutely no fear in trying atleast

#

rofl

cosmic dagger
#

the easy thing to note is that all of those words are synonymous with each other. they're all delegates, just called different names based on their use . . .

north oar
#

bro how do i edit keyframes when im in edit mode it just makes new keyframes and when im not in edit mode it just doesnt save the changes 🔮

rocky canyon
#

to me its more complicated b/c of how similar they all are

silk night
#

Idk if its just selective bias but I suddenly see many people using [field: SerializeField] instead of just [SerializeField], is there any difference or just syntax sugar?

rocky canyon
#

im 100% sure theres a difference in the two.. (soo more than just syntax sugar) specifcally? idk yet

silk night
rocky canyon
#

i think [SerializeField] is unity specific... and the other one is not.. and can be used to serilize backing fields of auto-implemented properties

#

backing fields? no clue lol but yea..

rocky canyon
polar acorn
swift sedge
#

oh, so it makes it work for properties?

silk night
polar acorn
#

Yes, because that's what they're called

silk night
#

aight, ty

rocky canyon
#
  • [SerializeField] for private fields you want to edit in the Inspector
  • [field: SerializeField] for auto-properties when you need Inspector visibility with encapsulated access
swift sedge
#

a sprinkle of complication

rocky canyon
#

hell ya 💪

#

good to know tho.. when i actually do start using more properties

timber tide
#

allows you serialize auto properties

#

such that you can make it a private setter, public getter

swift sedge
#

unity has a lot of attributes, so it's nice that it's still the same attribute name

timber tide
#

ye, and for all attributes if it's being applied to the auto property field you need to continue to use [field: ...] on it all

#
[field: Header("Settings")]```
lavish jolt
#

Hi, how can i get vector with this direction?

silk night
swift sedge
#

property fields are useful when you want a simple listener for when the property has changed

lavish jolt
silk night
rocky canyon
#

or -transform.right

#

depending on how its oriented

lavish jolt
#

-transform.up worked

#

Thank you

buoyant schooner
#

Is this a good way to check if player is holding mouse over a location in a grid in unity ?

When the mouse is clicked, see which square in the grid its in and keep checking if its still inside that square
And have a coroutine to have a hold timer.

#

I just checked out the hold interaction using the unity input system, however I need a way to be able to control how long the hold is depending on the type of object the mouse is hovering over.

rocky canyon
#

sounds like rolling ur own solution would be best if it were gameobject dependent

#

not sure tbh

buoyant schooner
#

hmm, I wanted to do it this way because they are tiles in a grid

rocky canyon
#

i'd ask around some more..

ebon mist
#

Does anyone have experience with GitHub I just overwrite my entire unity project trying to make a back up

polar acorn
#

How did you manage that

#

Did you delete any files, or use any sort of --hard git command?

ivory bobcat
#

Probably pulled instead of push

polar acorn
#

Still won't erase anything unless you --force it

ebon mist
polar acorn
#

Creating a new repository won't do anything to files on your computer

#

Unless you specifically deleted the folder, or used --hard or --force or some other git command that requires specific intent

ebon mist
#

Yeah that’s what I don’t understand unless I somehow deleted it prior to creating the repository I just noticed it was empty when nothing got pushed

#

Sorry kind of new to GitHub don’t really understand it all yet

polar acorn
#

What did you actually do? Are you sure you're not just looking at the wrong folder?

stuck palm
#

can you serialise nullable types?

#

like GameObject? something

cosmic dagger
# rocky canyon is that the *easiest* thing to do?

Sorry, I was AFK. Here's an example of the difference between them (Pulled from StackOverflow) . . .

I just met you,
And this is crazy,
But here's my number (delegate),
So if something happens (event),
Call me, maybe (callback)?

cosmic dagger
winter echo
#

dose anyone have rescorce for this question or youtube video to understand the consept

#

i did the projctile and the movement and the animales but the game over thingy and the spawing idk how

stable narwhal
#

Hey, question 🙂
Im using a script that reads out a spreadsheet, and i made a script where the data from the sheet (per row) gets put into a list,
is there a way for me to read out this element from the list into text?
so, lets say, the list has int ID + string NAME, how can i show that id + name in text ? cus i googled a bunch and cant really figure it out :/

wintry quarry
#

What part of it are you struggling with?
You put the data into a list of what? Strings?

#

"the list has int ID - string NAME" that's pretty vague. You should share more details.

stable narwhal
# wintry quarry "the list has int ID - string NAME" that's pretty vague. You should share more d...

im sorry!

    [CreateAssetMenu(fileName = "AppliesConfig", menuName = "Config/AppliesConfig")]

    public class AppliesConfig : ScriptableObject{

        public string sheetId;
        public string gridId;

        public List<AppliesConfigList> applies; 
        
        [ContextMenu("Sync")]
        public void Sync(){
            ReadGoogleSheets.FillData<AppliesConfigList>(sheetId, gridId, list => {
                applies = list;
                ReadGoogleSheets.SetDirty(this);
            });
        }
    }

    [Serializable]
    public class AppliesConfigList{
        public int ID;
        public string Name;
        public string Role;
        public int Age;
        public string Country;
        public bool Bool1;
    }
    

This basically

#

but now, i would like to get those things converted to text elements and such,
So i can change / look at them when i hit play

#

It’s probably easier then I think but I’m overthinking stuff I guess haha

ivory bobcat
stable narwhal
#

Yes correct

#

I want it in the scene, it’s visible in the editor indeed

eternal needle
ivory bobcat
#

Make a ui object reference the scriptable object and simply populate the text/label. I'm unsure if you'll be able to change the asset:scriptable-object permenantly during runtime release but you could probably write/send the updated data back to the Google sheets ect.

wintry quarry
#

(Instantiate one row per element in the list)

toxic frigate
teal viper
charred spoke
queen adder
#

memes allowed now?

#

anyways, item system help, I want to have an SO with item data, how do I store custom datas for different item types? like foods have a satiety property and weapons have attack speed and damage.. What's the best design here?

#

inheritance?

charred spoke
#

Inheritance is perfect for this type of deal

#

Although recently I have taken a liking to just using interfaces like IEdible for example

static cedar
#

Setting a LayoutElement property indirectly though a custom editor. With a float input field. For some reason, it's not updating properly.

#

If i can't get any ideas to fix it. I'm thinking of just create a task that calls SetDirty through reflection each gui frame for x times.

fossil valley
#

Can someone please explain to me how this code works. It's baffling me. It's meant to go with the new input system.

Vector2 inputVector = playerInputActions.Player.Move.ReadValue<Vector2>();

Whereas before, I had to write all that

Vector2 playerDirection = new Vector2(0,0);

    if(Input.GetKey(KeyCode.W)) {
        playerDirection.y = +1; 
    }
    if(Input.GetKey(KeyCode.S)) {
        playerDirection.y = -1; 
    }
    if(Input.GetKey(KeyCode.A)) {
        playerDirection.x = -1; 
    }
    if(Input.GetKey(KeyCode.D)) {
        playerDirection.x = +1; 
    }

Like how does it know to just ReadValue and understand -1 or +1 for this Direction. Insane

strong wren
timber tide
#

that input vector there I believe is just the callback if you wanted to use those values in code

fickle plume
vast hamlet
#

Hey, I'm looking to implement this 2D Controller into my first mobile game and make it so the movement will be controlled by a joystick. I already have the joystick set up and have installed the unity package but I'm not sure how I can implement this. https://github.com/Matthew-J-Spencer/Ultimate-2D-Controller

GitHub

A great starting point for your 2D controller. Making use of all the hidden tricks like coyote, buffered actions, speedy apex, anti grav apex, etc - Matthew-J-Spencer/Ultimate-2D-Controller

severe onyx
#

How would I go about debugging code that controls resolution and full screen mode and the likes?

silk night
#

Make a debug build

severe onyx
#

None of what I'm trying to test for applies to the normal editor play mode but obviously I can't read my debug logs in a regular standalone build

severe onyx
silk night
#

build settings

#

and then click Build and Run at the bottom

severe onyx
#

Will try it, thanks!

past spindle
#

I'm trying to addforce from one object's script to another object for a knockback effect but I'm missing something and could use another set of eyes.

private Rigidbody boxRb;

#

ah, ignore that

#

I'll just put it in a link

silk night
eternal falconBOT
past spindle
#

thankds

timber tide
#

Any of these debug.logs printing

past spindle
#

When they aren't commented out they all work

silk night
#

So what exactly is the problem rn?

#

Player isn't moved?

past spindle
#

I'm getting no actual force being applied

silk night
#
  1. You are looking for a counter component? Is that really the right one?
  2. Player input/movement might override the force
timber tide
#

OnCollisionEnter here isn't the object that's not being pushed right cause you're destroying it instant;y

silk night
#

Also is your Player kinematic or dynamic?

silk night
timber tide
#
    private void CheckForPlayer()
    {
        Collider[] colliders = Physics.OverlapSphere(transform.position, 3f);
        foreach (Collider c in colliders)
        {

            //Debug.Log($"Detected: {c.gameObject.name}");

            if (c.GetComponent<Counter>())
            {
                //Debug.Log($"Detected: {c.gameObject.name}");

                Vector3 direction = (transform.position - c.transform.position).normalized;
                boxRb.GetComponent<Rigidbody>().AddForce(direction * blast, ForceMode.Impulse);
                Debug.Log("Force was applied to boxRb");
                
                //Debug.Log("Player takes damage.");
            }
        }
    }

Few thing here, considering using TryGetComponent as that's less error prone and easier to debug against

past spindle
silk night
#

Oh and btw destroy has a time argument, like Destroy(gameObject, 0.1f)

silk night
timber tide
#

First thing to do is figure if it's a code issue and I'd make sure the component that being retrieved correctly, otherwise could just be not set correctly on the editor.

silk night
#

Oh yeah right you apply the force to the rigidbody of the sphere, not the player

past spindle
silk night
queen adder
#

I don't understad this error, can someone help?

past spindle
silk night
#

Also you can put a Script on c, which references the rigidbody in a public property, which you can then get off that script

timber tide
#

But if you're doing a cast using Overlapsphere, you should be getting the object with the collider, so if you're saying the parent of c is th eone with the rigidbody then it also must have a collider

past spindle
#

It has a collider but it's deactivated because it's a container

#

I think the getcomponentinparent might work but I gotta run the kids to school before I can try. Thank you all

timber tide
queen adder
#

i think so but let me double check

#

?ide

timber tide
#

But the issue reads that you're invoking a method but sending in the wrong parameters

queen adder
#

!ide

silk night
eternal falconBOT
queen adder
#

this is the code

north kiln
#

You can't use an int as input to a context menu method

#

There's no way you could provide that value via a context menu

queen adder
#

oops

#

lol

#

thanks

silver basin
#

is there a way to make a navmesh agent run out of a trigger?

timber tide
#

more context

silver basin
# timber tide more context

I want an enemy in my game to shoot a bullet and then run a certain distance away from the player before shooting another shot

timber tide
#

That's just logic then. Assuming your enemy is patroling via path calculations, you want some sort of detection method like OverlapSphere to hault the current pathing. Then, calculate a new pathing towards the player.

#

If enemy is atleast 5 units close to the player -> shoot
else continue pathing

#

If enemy shot a bullet, find a position on the navmesh 5 units away from the player and path there

silver basin
timber tide
#

Sometimes you may not get a position, so the idea is to fallback on a count of sampling. If you can't find one then that's up to you to decide how they should behave.

#

Lot of ways about this, such as having nodes on your scene you consider as cover which you can just use those as the position

craggy crypt
#

Hey, I'm a first-time coder and would like to learn how to add UI in my game?
I don't know how to insert my artwork as in what the resolution has to be for it to look good

Can someone help me to make a peice of UI where you can see the characters age,health,gender, and happiness things like that

wraith phoenix
#

Howdy there,
I'm looking to create a timer that will work with a collider area and track how long the player has been in that area. If they're in that area too long, it calls a function. When they leave the area, the timer stops.
Can anyone please help?

#
        uI_Fade.FadeToPurple();
        if(Time.deltaTime == timeUntilPoison) {
            playerHealth.Death();
        }
    }
    
    void OnTriggerExit2D(Collider2D other) {
        uI_Fade.FadeToClear();
    } ```
#

This is what I currently have but I feel like the if() is a little off.

gleaming kraken
#

is there any equivalent to a raycast that just makes a sphere with a specified radius around a transform, and checks if anything collides with that sphere?

slender nymph
cosmic dagger
#

@wraith phoenix Just a tip: instead of separate methods to fade for every color, make one FadeTo method with Color as a parameter . . .

#

Just check/compare its position with the world position . . .

gleaming kraken
# timber tide OverlapSphere

thank you! I did it in a very stupid way by just making a sphere trigger, and adding anything that enters it to an array and anything that leaves is removed from the array, but this is so much easier and i'd bet much more performant too.

cosmic dagger
#

There is a distance method to see how close the GameObject is to a position . . .

timber tide
gleaming kraken
slender nymph
#

if the gameobjects have a collider then a physics query like an overlapcircle would

wraith phoenix
timber tide
#

Mind you that rigidbody is only required to register the events, but can be set as kinematic

#

some physx bs

wraith phoenix
gleaming kraken
#

because colliders just aren't enough i guess

timber tide
#

blame nividia

#

meanwhile box2D allows you to invoke colliders directly

gleaming kraken
#

wait

gleaming kraken
wraith phoenix
#

is there a C# unity command that tracks time in a collider?

timber tide
gleaming kraken
gleaming kraken
slender nymph
timber tide
#

box2D you can just check if something is intersecting via collider

#

instead of having to use these events

wraith phoenix
gleaming kraken
slender nymph
#

you can check if something specific is touching the collider with the IsTouching method, but the methods like Collider2D.Overlap still require a rigidbody

gleaming kraken
#

unless you're talking about couroutines

timber tide
wraith phoenix
wraith phoenix
slender nymph
timber tide
#

Oh, I mean having to use the Trigger method specifically

#

Sorry yeah rigidbody is still required unfortunately

slender nymph
timber tide
#

It's just that I've a preference of doing stuff in Update primarily, so I'm not the biggest fan of just the general usage of OnTrigger() ect

#

so usually you fall back onto using the physic queries but it's something easily to work with on the editor visibly

#

Maybe I'll look into developing a small gizmos script per query for that specific gameobject

wraith phoenix
#

I did get some of the code to work.

#
        if (other.CompareTag("Player")) {
            Debug.Log("Player tag has worked with collider");
            poisonTime = timeUntilPoisoned;
        }
    }

    void OnTriggerStay2D(Collider2D other) {
        if (other.CompareTag("Player")) {
            Debug.Log("Player has entered Poison");
            uI_Fade.FadeToPurple();
            poisonTime -= Time.deltaTime; 

            if (poisonTime <= 0) {
                Debug.Log("Poison time has reached zero and if statement fired");
                playerHealth.Death();
            }
        }
    }

    void OnTriggerExit2D(Collider2D other) {
        if (other.CompareTag("Player")) {
            uI_Fade.FadeToClear();
        }
    }```
#

My uI_fade is not wokring but the poison area kills me after 3 seconds

slender nymph
#

depending on what your FadeToPurple method actually does, you might be restarting the process over and over

wraith phoenix
#

I likely need to move it to OnTriggerEnter

#
        if (fadeRoutine != null){
            StopCoroutine(fadeRoutine);
        }

        fadeRoutine = PoisonFadeRoutine(1);
        StartCoroutine(fadeRoutine);
    }

private IEnumerator PoisonFadeRoutine(float targetAlpha){
        while (!Mathf.Approximately(poisonFadeScreen.color.a, targetAlpha)){
            float alpha = Mathf.MoveTowards(poisonFadeScreen.color.a, targetAlpha, fadeSpeed * Time.deltaTime);
            fadeScreen.color = new Color(poisonFadeScreen.color.r, poisonFadeScreen.color.g, poisonFadeScreen.color.b, alpha);
            yield return null;
        }
    }
#

Here is my fade FadeToPurple method

#

not sure why it isn't firing

slender nymph
#

put some logs in there to see what is actually happening

solar moth
#

I'm encountering the weirdest thing I have ever seen. I'm creating a new empty scene, add an empty GameObject and add the following script:

public class AuthManager : MonoBehavior
{
  public static AuthManager Instance { get; private set; }
  // some other fields
   [SerializeField] private string baseUrl = "http://localhost:8000/api";
  // etc. (but nothing special)
  private void Awake()
      {
          Debug.Log($"AuthManager Awake called. {Instance == null}");
          // Implement Singleton pattern
          if (Instance == null)
          {
              Instance = this;
              DontDestroyOnLoad(this.gameObject);
          }
          else
          {
              Debug.Log("Duplicate AuthManager detected. Destroying.");
              Destroy(gameObject);
              return;
          }
  
          DontDestroyOnLoad(this.gameObject);
      }
  }

The gameObject get's destroyed after seing AuthManager Awake called. True in the console. And there is no Duplicate AuthManager detected. Destroying in the console either. It makes zero sense to me.

slender nymph
slender nymph
solar moth
#

But it disappears and the start method is not called.

slender nymph
solar moth
slender nymph
#

did you look in the DDOL scene where DDOL objects go?

solar moth
slender nymph
#

i see no Start method on that component. so how have you actually confirmed any of this

solar moth
#

I've created a new Empty Script:

public class Test : MonoBehaviour
{
    public static Test Instance { get; private set; }
    // some other fields
    [SerializeField] private string baseUrl = "http://localhost:8000/api";
    // etc. (but nothing special)
    private void Awake()
    {
        Debug.Log($"AuthManager Awake called. {Instance == null}");
        // Implement Singleton pattern
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(this.gameObject);
        }
        else
        {
            Debug.Log("Duplicate AuthManager detected. Destroying.");
            Destroy(gameObject);
            return;
        }
  
        DontDestroyOnLoad(this.gameObject);
    }

    public void Start()
    {
        Debug.Log("Start called.");
    }
}

Could I be doing something else wrong?

slender nymph
#

did you put this component on anything?

solar moth
#

Sorry, it was something different 🤦

#

I didn't know about the DDOL

languid spire
solar moth
odd widget
#

Elo again

#

Is there a way to check if the gameobject that i’m dragging in on top of another object

#

The way that i drag is to directly change the object position usinh OnDrag object.transform.position = mouseposition, not rigidbody speed

#

It’s 2D

#

But i’d still appreciate it if there is a better way

queen adder
#

Hallo, I have a quick question. I’m new to unity, how to change the background colour in unity 6(I can’t find it under main camera)

night raptor
#

and how is this code related?

#

Camera.backgroundColor should definitely still exist in unity 6

past spindle
#

Why would I not be able to drag a Canvas Text object into a public variable I created for it?

hexed terrace
eternal falconBOT
past spindle
#

public Text hpText;

hpText.text = "Box Health: " + boxHealth;

slender nymph
#

your text object is very likely a TextMeshProUGUI object, not a legacy Text object

past spindle
#

yeah, sorry

hexed terrace
#

use public TMP_Text hpText; instead

night raptor
#

TMP_Text? since when that existed?

polar acorn
hexed terrace
#

It's the base class for the two TextMeshPro classes

polar acorn
#

It's the shared parent class of both TextMeshPro and TextMeshProUGUI

hexed terrace
#

and probably others

night raptor
#

seems to be, learn something new every day

past spindle
#

I'm using Text in another script and it works fine. Why would it be different here?

hexed terrace
#

because you're using legacy text component with it..

polar acorn
#

Is that other script referencing an actual Text object instead of a TextMeshProUGUI object?

#

They're different components

#

They aren't interchangeable. You can't use a variable of one type to reference the other, in either direction

past spindle
#

wait...I think I see

polar acorn
#

Show the inspector for the object that does work, and the one for the one that doesn't

past spindle
#

what's the library declaration for the TMP?

slender nymph
#

use the quick actions in your IDE to add the correct using directive

past spindle
#

Still ot able to add it and I'm getting this error on my 2nd line of script: Severity Code Description Project File Line Suppression State
Error (active) CS1061 'TMP_Text' does not contain a definition for 'TMP_Text' and no accessible extension method 'TMP_Text' accepting a first argument of type 'TMP_Text' could be found (are you missing a using directive or an assembly reference?) Assembly-CSharp C:\Users\joshu\OneDrive\Desktop\Unity Projects\Counting Prototype\Assets\Scripts\BoxController.cs 50

#

(not)

polar acorn
languid spire
#

why do you think the namespace for TMP_Text is TMP_Text ?

past spindle
polar acorn
#

No one, at any point, said to change the variable

languid spire
#

don't assume, check

polar acorn
#

You need to change the type

past spindle
#

my bad

#

ok, that got me over the hump. Thank you

#

is variable--; the right line of code to subtract 1 from variable?

swift sedge
#

yes

#

it's the shorthand of doing variable -= 1

past spindle
#

Sorry for so many questions. I enjoy the coding aspect., but there's just so much to remember. Is there like a good reference sheet for beginners that anybody can recommend?

slender nymph
#

there are beginner courses pinned in this channel

eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

burnt vapor
past spindle
#

I'm actually taking the junior programmer course through UnityLearn, but doing and remembering are two different things

swift sedge
swift sedge
#

if you write a player controller many times, then you will be able to write a player controller without even thinking about it

dark apex
#

Hi! :3

dark apex
#

Does anybody know a 3D movement code?

#

Or 2D

slender nymph
#

there are hundreds of tutorials for that

dark apex
#

ok

gentle fog
#

Guys can anyone tell me how do I add 2 pieces of string together?

slender nymph
#

there are beginner c# courses pinned in this channel, if you are not aware of the + operator, then perhaps start there

polar acorn
#

if not, you're going to have to actually say what you mean by "adding" and "piece of string"

gentle fog
#

I already solved the problem.

raw loom
#

how do i change the material of an object thru a script? like if i want to change a ball to use a different texture by pressing a button

gentle fog
slender nymph
#

text mesh pro had nothing to do with converting the numbers to a string. its text property is a string and can only have a string assigned to it.

raw loom
slender nymph
#

you can change the entire material with that property

raw loom
#

oh i see

slender nymph
#

the code example is merely just an example of getting the material. that is not the only thing you can do with it

polar acorn
past spindle
#

For changing a variable in another script, you gotta declare the variable, define it in start, and do the math your wanting to do, but what sends the data back to the script you got the variable from in the first place?

polar acorn
#

That doesn't seem like what you do for changing a variable

steep rose
#

you have to reference the script if which containts the variable you want to change then change that variable like so
public Script _Script;, _Script.Var1 = etc;

past spindle
#

Then I’m doing it wrong lol

polar acorn
#

You don't get a reference to a variable

#

you get a reference to the object that has the variable

carmine sierra
#

I wanna make a cue which can rotate as it moves around the ball, where can I start?

#

I tried the lookat method but it rotated it in axis' i didn't want

rich adder
#

You could also potentially give it a parent object whos origin is always at the ball when shooting, and use regular rotate methods

dreamy bear
night raptor
#

Parenting would also make it easier to make the shooting animation etc. because you could just move on local axes

carmine sierra
#

Is it?

rich adder
# carmine sierra Is it?

nahh not at all . SetParent function works very well , just move the pivot item to the ball when you setup for a shot

night raptor
carmine sierra
#

I need to rotate it around the ball

rich adder
carmine sierra
#

so i make the pivot a child of the ball?

rich adder
#

no because if you move the ball everything will follow the ball, all you need is to set that parent position to the ball

carmine sierra
rich adder
carmine sierra
#

ohh

#

couldnt i just make the cue a child of the pivot though

#

the ball i mean

rich adder
#

you could but after you hit the ball you must unparent it

#

otherwise any child (including the cue) will follow the ball

carmine sierra
#

oh ok

carmine sierra
#

i have the pivots position and the cues position (where it follows the mouse)

rich adder
carmine sierra
#

yeah i get that

#

but idk how the cue will understand what angle to point in

#

cause it will rotate with the mouses position

#

i assume i need to take the distance between the two and do smth but idk what it is

dreamy bear
#

You want to target where the mouse is pointing ?

rich adder
#

that depends on how you plan on rotating , its behaviour

carmine sierra
#

at the cue balls position

rich adder
#

the pivot will be your rotation

carmine sierra
#

yeah

#

but the mouse will move to change the rotation

rich adder
#

usually transorm.up is your direction

#

you could rotate the Z with for example the delta of the mouseX

toxic frigate
waxen adder
#

If I don't indicate a parent when defining a class, does it automatically have Object be the parent?

rich adder
#

like a parent class

carmine sierra
waxen adder
#

So like [ClassName] : Monobehaviour.

iirc that means the class is a child of monobehaviour, so what happens if nothing's there? Is Object the parent?

fast briar
#

Hi all, im getting this error and it doesn't quite make sense as i have followed the naming convention required?

Rpc method must end with 'Rpc' suffix!

[Rpc(SendTo.Server)] void CastSpellRpc(int spellNumber){ unitStats.Cast(spellNumber); }

slender nymph
rich adder
carmine sierra
teal viper
slender nymph
rich adder
carmine sierra
#

It needs to know when its going above or below

rich adder
fast briar
carmine sierra
#

like 8 ball pool

#

i want it

slender nymph
rich adder
carmine sierra
slender nymph
fast briar
#

doesnt look like the issue

slender nymph
#

if you are certain that your code has been compiled and you are still receiving the error, then screenshot both the full error (including stack trace) and the inspector window when you've got the script selected so it shows the code that unity sees

rich adder
#
   void Update()
    {
        var mouseWorld = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        mouseWorld.z = 0;
        var dir = mouseWorld - cuePivot.transform.position;
        cuePivot.up = dir.normalized;
    }```
fast briar
slender nymph
#

that error is stale. clear it

fast briar
#

doesn't clear and won't build because of the error. it goes away if i change it to not use RPC and comes back when i add it again

waxen adder
#

Are there variants of UnityAction that support non-zero arguments?

slender nymph
carmine sierra
#

I was confused why up was relecant

#

relevant

rich adder
fast briar
#

without [Rpc(SendTo.Server)]

#

then when i re-add it comes back

slender nymph
fast briar
rich adder
slender nymph
rich adder
#

just to try and see if it works

slender nymph
#

fwiw i'm not having any issue with using the RPC attribute 🤷‍♂️

waxen adder
rich adder
#

why not just use the System.Action , whats the benefit of UnityAction over that

fast briar
#

well, doesnt matter anyway it seems

rich adder
fast briar
#

[ServerRpc] void CastSpell_ServerRpc(int spellNumber){ unitStats.Cast(spellNumber); }

rich adder
#

yeah idk ur seetup is bugged

fast briar
#

ok ty ill ask in networking

waxen adder
rich adder
rich adder
carmine sierra
#

without animating

rich adder
carmine sierra
#

I did forward it kind of works

#

but it keeps angling on the z axis

#

i mean x axis

rich adder
#

make sure its in Local mode not Global

carmine sierra
rich adder
#

yes you want transform.forward if thats Local mode

#

cast the mouse onto a plane here (if you're doing topdown)

carmine sierra
#
        if (Physics.Raycast(ray, out RaycastHit raycastHit)) {
            _mousePos = transform.position = new Vector3(raycastHit.point.x, 0, raycastHit.point.z);
        }```
#

I did that

rich adder
#

so based on that example I sent, it would be
var dir = worldPoint - cuePivotTransform.position cuePivotTransform.forward = dir.normalized
just make sure the plane is in the correct axis

carmine sierra
#

yh

#

when it comes closer

rich adder
#

did you use the plane?

#

no need for a reg raycast here, use the plane so its flat

carmine sierra
#

why would plane be better

#

also what is that

rich adder
carmine sierra
#

yes

#

thought it was just for 2d

rich adder
carmine sierra
#

oh okay

waxen adder
#

Man, delegates are such a weird concept. Still trying to get a grasp on them

zenith cypress
#

They are basically just a function stored in a variable

eternal needle
#

been awhile since i watched it but i believe up to video 14 is all you need for unity stuff anyways

waxen adder
#

Yeah, I might look into that. I get the whole thing of them being a function in a variable, but their use case is kinda beyond my imagination. If I hadn't had to deal with them when modding a game, I doubt I would use them

rugged remnant
#

Could someone help me fix a bug is beginner stuff I can screenshare

eternal falconBOT
eternal needle
waxen adder
#

Hmm. So are they more closely used in events among other things? That would make sense

eternal needle
#

events are basically restricted delegates

#

event is just a keyword

rugged remnant
# rich adder !ask

I have this problem rn where the script editor would open but just show up blank

rich adder
#

also you should probably update to latest VS (2022)

rugged remnant
rich adder
#

you can make a thread too, so we don't flood chat

rugged remnant
#

yeah lets do that

#

fixing vs code not opening

teal viper
zenith cypress
# waxen adder Yeah, I might look into that. I get the whole thing of them being a function in ...
  • Run some function when you click a button, or multiple functions
  • Detect if an actor gets damaged
  • Detect if the scene changes
  • Detect if a tween is complete
  • Detect if the editor's play state changes
  • Delay an editor action via EditorApplication.delayCall to call a function on the next editor frame

etc etc, many use cases where you basically want to "emit" an event for any number of "listeners" to get that emission later.

waxen adder
#

If I'm thinking in that particular area/scope, it makes more sense

zenith cypress
#

Yes. Also bawsi was talking about the literal event keyword which can be put onto a delegate variable so only the thing that holds it can actually run it.

waxen adder
#

Oh I see

rich adder
#

@limber epoch enum is basically human-readable labels for integers

limber epoch
#

oh

#

i need to read more unity

rich adder
#

this is c# stuff. I suggest you check out the docs

limber epoch
#

thanks

glad nebula
#

!ask

eternal falconBOT
silver basin
#

Is there a way to make one transform's rotation smoothly match another transform's rotation?

naive pawn
#

set it in LateUpdate?

cinder schooner
silver basin
#

Alright Ill do that

night raptor
# silver basin Alright Ill do that

Also Lerp Smoothing might be something to look into. People usually do Lerp(current, target, Time.deltaTime) but that's not truly framerate independent

languid spire
night raptor
#

didn't I just tell not to?

candid gate
#

Hello, i have an issue with my character controller script, for some reason its offset by like .15 from the ground, its the first time i use characterCDontrollers instead of rigidbody

languid spire
#

yes, Lerp is start,end,t not current,end,c

buoyant finch
#

hello I am making a 2d rpg and in it I have an npc who I want to follow a fixed path for 1 event another fixed path for another and so on pls guide me on that

night raptor
#

Lerp Smoothing is a great tool to make smooth following animations procedurally

candid gate
#

oh

rugged remnant
#

I just loaded my project and out of nowhere it looks like everything is gone

languid spire
rugged remnant
#

what do I do to fix it

candid gate
#

and the scene is saved

languid spire
#

open a scene, usually in Scenes/SampleScene if you changed nothing

candid gate
#

wait, isnt a scene supposed to be chached in Temp ?

languid spire
rugged remnant
candid gate
#

tho you cant have no scene without no scenes or am i wrong

#

you cant unload it

#

so idk

languid spire
# rugged remnant

why are you looking in file explorer, look in the unity project view

rugged remnant
languid spire
#

Ignore

rugged remnant
#

yeah same thing

#

it wa snot like this 5 hrs ago

#

the scripts everything there

languid spire
#

screenshot your project view

rugged remnant
languid spire
#

in the Editor not the Hub

rugged remnant
candid gate
#

Now go in the Scenes folder

languid spire
#

so open the scenes folder

#

then open Sample Scene

rugged remnant
#

oh yeah got it

#

thank u

languid spire
#

you really need to !learn

eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

candid gate
#

same for me

rugged remnant
candid gate
#

show console

rugged remnant
languid spire
#

yep, that is your next job, fix your compile errors

candid gate
#

is it normal that even in fixedupdate, how my character controller jump is random

        // Handle jumping input
        if (Input.GetKeyDown(KeyCode.Space) && groundedPlayer)
        {
            // Set the vertical velocity for jumping
            playerVelocity.y += Mathf.Sqrt(jumpHeight * -2.0f * gravityValue);
        }
candid gate
languid spire
#

probably missing the Unity.UI package

swift sedge
#

or doesn't have the using

rugged remnant
languid spire
#

look in the package manager

languid spire
candid gate
#

oh

#

neither in update

#

so when ?

languid spire
#

Only in Update and cache the value

candid gate
#

wait what

#

i always got told to check input in fixed

languid spire
#

Wrong

candid gate
#

oh maybe because it was a rigid body too...

languid spire
#

nope, never check for Input in Fixed because it does not run every frame

candid gate
#

wtf are those tutorial i watched lmao

languid spire
#

like most tutorials, rubbish

candid gate
languid spire
#
bool keyPress
...
Update
   if (Input,GetKeyDown) keyPress = true
FixedUpdate
   if (keyPress) {
    // Your code here
    keyPress = false;
   }
candid gate
#

oh

languid spire
#

<@&502884371011731486> Spam

candid gate
#

also funnyt part, its not even automated lmao

#

you would think they would be smart, but nope

#

MEE6 Is so powerfull it run on a phone

north kiln
#

!ban 1295969937931636791 bot spam

eternal falconBOT
#

dynoSuccess valiant_quokka_11852 was banned.

candid gate
languid spire
eternal falconBOT
candid gate
#

oh never mind, for some reason unity didnt refreshed the first time

queen adder
#

how do i make a function for a event to trigger when you hold a key down

#

when i use void update it just keeps going and going when im holding that key down

#

i want it to only happen once when i press it down

swift sedge
#

you can use a coroutine

queen adder
#

Sorry

queen adder
#

how do i make a script to tell every single gameobject with a tag to do something

#

or just disable a component from them

naive pawn
#

you could use FindGameObjectsWithTag

silk night
#

If there is no way around doing that by tags the answer above is your choice but thats generally not something you want to do

hexed terrace
#

Don't want to do it often.

Once at the start during/after load is fine

#

The question is too vague to give the best way for this situation though. There are too many ways to do this and the best way depends on the specific use case.

gleaming kraken
#
private void Update()
{
        // ... (Other code)

        Vector2 direction = lookAtObject.transform.position - transform.position;

        float lookDirection = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;

        transform.rotation = Quaternion.Euler(0, 0, lookDirection);

        spriteRenderer.flipY = transform.position.x > lookAtObject.transform.position.x;
}```

is this a clean way to implement an object looking at another object? (2D space)
timber tide
#

if it works it works

languid spire
gleaming kraken
#

or i might be using it wrong

#

by just putting in the object I want it to look at

#

rather than the look direction

timber tide
#

this is top-down?

#

as you're using atan2

#

funnily enough, you can use quaternion's methods too (z-up)

gleaming kraken
past spindle
#

I used OverlapSphere to create a knockback effect, but it sends the player through the epicenter if they are running toward it instead of knocking them back. Recently ai was told player movement can override addforce and I was wondering if stopping the player movement prior to the addforce would fix that or if there was a simpler solution?

slender nymph
#

it depends on how you are moving the player. if you're using anything other than addforce to move them, then yes you will need to stop their movement ability for the duration of the knockback so you don't completely override it

past spindle
#

Ok, thanks

wintry quarry
drowsy oriole
#

Can someone help me make a script that changes a scene?

#

I want it to be a button tho

devout flume
# drowsy oriole Can someone help me make a script that changes a scene?

We don't spoonfeed scripts here, I'm sure there are plenty of tutorials to achieve that, you may also want to check the documentation. I know for sure that in the beginner pathway on !learn, there is a final step that introduces you to scene management & scripted buttons to teleport from one scene to another

eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

static cedar
#

How to get the minimum width and height of a rect transform using properties of various child layout elements?

long maple
#

Hey, just wondering if anyone can help, im struggling with a jittery moving platform. im not sure if my code is the issue. Any help would be massively appreciated. ( the code works fine for side to side transformations but is jittery on up and down)

wintry quarry
#

that's your issue

#

You need to give your object a Rigidbody if it doesn't have one, turn on interpolation, and move it in FixedUpdate with Rigidbody.MovePosition

long maple
final kestrel
#

When I do SceneManager.LoadScene("some scene name"). It will get rid of all the additively loaded scenes and just load a whole new scene?

wintry quarry
onyx tusk
#

how 2 add text 2 3d objects?

wintry quarry
#

You can either add 3D text objects to the world

#

or use a world space canvas

#

or embed text in a texture/material

#

Really depends on the effect you want

onyx tusk
#

i want 2 make ui with code

hexed terrace
#

!vs

eternal falconBOT
#
Visual Studio guide

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

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

final kestrel
#

https://hatebin.com/aqyeiknpdg
So this is my Loader class. I want to go to Loading Screen first. Then when on Loading Screen scene, after first update, it fires the callback saying the scene is loaded. Then I want to load the scene name I pass in additively so i do not destroy my Init scene which is loaded from the start of my game. For some reason when I press load. It loads Loading screen scene and playable scene again and again.

rocky canyon
swift sedge
#

This isn't even unity related

wintry quarry
#

maybe contact github support

delicate portal
#

I deleted it just in case

final kestrel
onyx tusk
#

y i don't see the text?

cosmic dagger
#

have you tried resizing the boundary box, or using one character to "W" to see if it fits/appears?

naive pawn
#

is Font Asset supposed to be unset?

#

yeah pretty sure it's not supposed to be

#

@onyx tusk try setting that field

onyx tusk
#

how 2 add font?

cosmic dagger
#

does the same thing happen when you create a new text mesh pro GameObject?

cosmic dagger
#

this is a GameObject with a text mesh pro component, right? just create a new one . . .

onyx tusk
#

i used this

onyx tusk
naive pawn
hexed terrace
#

That's not the font TMP wants, you need to create an SDF file.

queen adder
#

how do i make a reverse event

#

like instead of invoking the event the event gets invoked by something else

naive pawn
hexed terrace
#

also, this is a non-code question in a code channel. Should be asking about this in #📲┃ui-ux

naive pawn
#

but also, you should have liberation sans by default?

hexed terrace
#

The text won't be displayed if the TMP essentials aren't imported... no idea if the default font is imported with that or not

#

as he's got no font asset assigned, I'd assume it's imported with the essentials

swift sedge
# onyx tusk

you need to generate a font using the TMP font generation tool

hexed terrace
#

needs to import TMP essentials first

cosmic dagger
#

you don't need to generate a font to use TMP. they have a default . . .

naive pawn
hexed terrace
#

for some reason

Becuase, for the third time, they don't have the TMP essentials imported 😄

cosmic dagger
#

i thought their original issue was trying to add text to 3d objects?

queen adder
#

how to make a variable avaible for the whole scene

cosmic dagger
#

i hope they imported it by now, lol . . .

hexed terrace
# onyx tusk y i don't see the text?

There's no font assigned here by default.
They get no font asset in the drop down, because none are present.
The default font isn't present because they haven't imported the TMP essentials

naive pawn
hexed terrace
queen adder
dawn hazel
# queen adder i still dont understand

There are a lot of ways to pass information between objects, which strategy you want to go for really depends on what you're trying to do. Take a look at singletons. You can only have one instance of a Singleton, so you'll have a static method for accessing that instance. Let's say you want to track score in such a way that any object can read or modify the score, you could have a ScoreManager singleton with a score int, then if you want to add 100 points to the score from any script, you'd just do something like ScoreManager.Instance.addPoints(100);

gray coral
#

Would turrent defender game considerd beginner friendly? how long would it take to code something like that simpel

wintry quarry
#

Turret*?

#

you mean tower defense?

past spindle
#

Vector3 direction = (transform.position - c.transform.position * -1).normalized;
c.GetComponentInParent<Rigidbody>().AddForce(direction * blast, ForceMode.Impulse);

#

Anybody know why this would push the player away from 0,0,0

keen dew
#

transform.position - c.transform.position * -1 is the same as transform.position + c.transform.position

keen dew
#

If you want to reverse the direction, swap the positions: (c.transform.position - transform.position).normalized

final kestrel
#

When I load a scene additively while im still on the say loading screen. The additively loaded scene's awake methods will get called right?

wintry quarry
final kestrel
wintry quarry
#

It will do whatever you told it to do in Awake

#

if that includes "looking for objects", certainly.

final kestrel
#

Yeah like. I think my additively loaded scene looks for the camera object inside the loading scene.

#

Its possible yeah?

wintry quarry
#

if you wrote it that way

cosmic dagger
#

is that what you told it to do?

past spindle
#

Hey, that seems to have worked, reversing the positions. Thanks

wintry quarry
#

I do believe if you delay scene activation, you might be delaying Awake/OnEnable.

#

but it's not clear

final kestrel
#

I mean no I do not want it to be clear. I just want it to call awake if the scene is loaded but i guess i am not doing it. Because in my newly loaded scene, when it gets set active, even though I have a camera, it says camera is destroyed. I believe it is because awake gets called in my new scene while im still on the loading scene because of additive loading. Finds the loading scene camera, when the loading scene gets unloaded it loses the reference and never tries to find again

wintry quarry
#

sounds likely

#

You might need to evolve beyond whatever naive method you are currently using for finding the camera

final kestrel
#

Thats right. I need to evolve. Thanks for the help

#

Wohooo! I delayed the finding camera and it works.

queen adder
#

I have this line off code, but it return null, if i restart the game, any idea why?

#

void Awake()
{
logic = GameObject.FindGameObjectWithTag("Logic").GetComponent<LogicManagerScript>();
}

wintry quarry
#

what do you mean by "restart the game"

#

you'd have to explain how you're doing that

#

and on which object this script lives, etc..

queen adder
#

public void restartGame()
{

    SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
#

tis is my restart func

#

the logic manager is in the scene tree

wintry quarry
#

what actually issue or error are you seeing

queen adder
#

The Error: Nullreferenceexception,object reference not set an instance an object PipeMiddleScript.OnTriggerEnter2D. sc 23)

#

is the error that pops off

#

btw is there a better way to writhe code in discord ?

eternal falconBOT
queen adder
#

thx

#
using Unity.VisualScripting;
using UnityEngine;

public class PipeMiddleTriggerScript : MonoBehaviour
{
   public LogicManagerScript logic;

   void Start()
    {
        logic = GameObject.FindGameObjectWithTag("Logic").GetComponent<LogicManagerScript>();
    }

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

    }

    private void OnTriggerEnter2D(Collider2D collision) 
    {
        if (collision.gameObject.layer == 6)
        {
            logic.addScore(1);

        }


    }
}
#

and now the error appers, if the tirgger gets triggert. i seem like the logic is null, but why ?

slender nymph
#

if there is no exception being thrown in Start then whatever object is tagged with Logic does not have a LogicManagerScript component attached

queen adder
#

this is the whole game, the logic (gamecontainer) was the script

#

and i really don't understand why unity didn't find the logic script

slender nymph
#

make sure that is the only object tagged as Logic in your scene

queen adder
#

OHH MY GOD!! Somehow the EventSystem also got this tag. 2 Hours wasted

#

The sultions was so dumb easy, thank you!!

void thicket
#

Now is good time to rethink the decision to use tags

slender nymph
queen adder
#

I follow an youtube video.. ohh man, anyway i take a look at this. Thanks again !

wintry quarry
#

It's always better to actually debug your code than just guessing

tough sundial
#

Could anyone help me with something?

cosmic dagger
steep rose
eternal falconBOT
tough sundial
#

!ask

steep rose
#

read the bot

#

dont actually use the bots command

tough sundial
#

I’m trying to generate a maze and this is the result.

#

I don’t want it to generate an incomplete one.

#

Any suggestions?

slender nymph
night mural
shrewd matrix
#

yo is there a way that i can tag something twice? Because i am making a card game and need something for all cards and just per classes.

wintry quarry
#

make your own custom component and you can put whatever data on it you want.

#

Using tags is very limiting.

shrewd matrix
rotund bronze
#

anyone have any idea why input.getkeydown doesnt work on behaviour graph update state?

wintry quarry
rotund bronze
wintry quarry
rotund bronze
carmine sierra
#

any way to make a plane to a limited size?

#

When making a turn by turn game, what is the general design to schedule turns and moves etc

rich adder
carmine sierra
#

the onmousedrag function only recognizes when the mouse drags on colliders which are on the parent or children of the parent right?

#

cause I did onmousedrag when the parent has no collider, only a child has one

rich adder
carmine sierra
#

but the script and collider isnt on the same object, unless colliders on the children count

rich adder
carmine sierra
#

it worked, was just trying to make the pool cue move only when holding mouse down on it

carmine sierra
#

On the docs I can't see anything ab it

rich adder
#

you would have to replace it with maybe a box collider and do a collider.Raycast

carmine sierra
#

Is having two colliders on one gameobject, each with a different purpose, a bad idea

carmine sierra
rich adder
carmine sierra
#

okay nice

rich adder
#

probably not what you want though, you should be fine with plane. How come you need specific size

carmine sierra
#

I am playing pool on a table

#

but the current mechanic isn't working how it will in the end

carmine sierra
#

rn it can move anywhere, in reality it will have to move and rotate around the ball in orbit (like 8 ball pool)

carmine sierra
#

How could I restrict it's movement in an orbit

#

a circle

rich adder
#

are you not rotating around the ball with pivot?

carmine sierra
#

yeah that worked

normal turret
#

Hey guys, what's up...?

#

Just to make sure, which one is better for the new Input System

#

Invoke C# Events or Send Messages...?

#

I mean right now I'm using Invoke C# Events and it works, but if I had to call my methods (when I make a state machine later), I don't think it's letting me do that

#

Well...I don't know how to call methods with Input CallbackContext as the parameter

zenith cypress
#

I just use the actions directly, so I don't use either.

normal turret
#

With the InputAction reference thingy...?

zenith cypress
#

You can assign actions to a variable in the inspector with InputActionReference. Then you can use the events yourself like .action.performed += MyEvent;. Otherwise if you are starting out, try out all the options to find a way that you think works best for yourself 😄

normal turret
#

Yeah that's true, I'll test it out, thank you

hexed terrace
normal turret
#

At the moment I'm using Invoke method and I think it works good

#

But if I had to call those methods inside a state machine I might build later, how would I do that...?

#

Because the parameter is a weird Callback Context thing, I'm not sure how I can "call" that

hexed terrace
#

InvokeMethod uses a string to... don't use it

odd epoch
#

do i send the code

#

bc

#

ye

hexed terrace
#

Already told you ... !code

eternal falconBOT
north kiln
# odd epoch

If your IDE has not underlined errors in red you also need to configure it

#

You've most likely named your own class SceneManager

odd epoch
#

its made by oculus themselves

hexed terrace
odd epoch
#

i was on 2021.3.33f1

#

then i switched to

#

2022.3.51f1

hexed terrace
#

It's not present in the docs until 2022.2

odd epoch
#

do i delete it?

hexed terrace
#

no..

#

you use a version 2022.2 or newer...

#

which, 2022.3.5 is

#

trigger a recompile

odd epoch
#

i switched to 2022.3.51f1 and some stuff stopped working

hexed terrace
#

yeah, that's possible.. gotta fix it

odd epoch
#

yeah but im talking big stuff

#

like it broke my entire hat system

hexed terrace
#

you have 2 choices
1- update and fix all the stuff that breaks
2- you can't use this from oculus

#

or..
3- fix the oculus code to work with 2021.3.33 -> biggest task

north kiln
carmine sierra
#

Just gonna have player 1 turn, player 2 turn and the phase when the ball is hit and is moving (in pool)

queen adder
#

how do i make a script using events that get invoked instead of invoking and works for multiple gameobjects

hexed terrace
#

this question is super vague and senseless

queen adder
#

okok

hexed terrace
#

Just be a bit more specific with what you’re wanting to do

queen adder
#

sorry

queen adder
#

uhh what do i use to change camera background color

#

vector4 ?

teal viper
queen adder
#

oh

opaque fox
#

Anyone know how to make text disappear behind this image as it scrolls? Does it need to be in another layer behind this one?

remote osprey
#

wdym?

#

Behind the image?

opaque fox
#

yeah, like it disappears either once it scrolls into the image's border or before it

remote osprey
#

It needs to scroll upwards but also toward the image?

#

you can just change its visibility once it crosses the border

#

There's probably a doTween to make an animation for that

#

You'll need to make each line be a separate object

#

And each object has a trigger event or you can just coordinate the animation with DoTween to do what you want to do

#

Hope it helps

toxic frigate
#

does anyone know why this doesnt wait for a time between 1 and 5 seconds?

IEnumerator DelayedExplode(Transform gun)
    {
        yield return new WaitForSeconds(Random.Range(1, 5)); // Wait for a random duration between 1 and 5 seconds

        // Detach and explode the gun after the delay
        GunDetachAndExplode(gun);
    }
teal viper
#

Try adding logs before and after the wait and see the time difference in the console

rich adder
flint gyro
#

trying to learn csharp, thinking about watching an older tutorial from freecodecamp, 6 years old, does that matter or should i look for something newer

teal viper