#💻┃code-beginner

1 messages · Page 67 of 1

harsh owl
#

thats not from gpt my guy

rich adder
#

really cause only bots comment every line even obvious ones

harsh owl
#

i did it for myself

rich adder
#

anyway, are we supposed to guess what ur variable values are

harsh owl
#

sec

rich adder
eternal falconBOT
harsh owl
#

ik

rich adder
#

"ik" ignores instructions

#

nice

harsh owl
#

why tf is it copying it as a txt file in here

rich adder
#

did you read the bot

#

specifically Large Code Blcoks?

harsh owl
#

ah i forgot that wasit

polar acorn
#

!code

eternal falconBOT
harsh owl
visual delta
#

I dont really know if this is the right place to go for this or not but why wont it let me put this script on i dont get it

keen dew
#

You're supposed to put a gameobject there that has the script attached as a component, not the script itself

rich adder
eager elm
visual delta
#

I put it under an empty game object and it still wont let me drag it in

rich adder
#

you cant add scene objects/scripts into a prefab slot

visual delta
#

😞

polar acorn
#

Scene objects only exist when that scene is loaded. Prefabs exist everywhere.

tribal axle
#

Hello! I am making a 3D game where enemies are being spawned continuously, and I want to know how to remove them when they surpass a certain Y point, I tried to do it inside of a loop, but it just waited until it got deleted and then spawned the next one. Tell me how should i fix this? Here is the code: https://paste.ofcode.org/Xnt6s5AvqSSxPdi8bAikF

rich adder
#

in Update

wintry quarry
timber tide
#

Coroutine is overkill for this. You've already a loop called update in each gameobject.

#

rather, what you need is a enemy script for each gameobject to reference.

rich adder
#

if obs have script with their own update mind as well do that

tribal axle
#

how do i add the delay then?

rich adder
#

they mean a timer in update

timber tide
#

Right, let the enemies keep time of themselves, and when they die you can either tell the spawner it has died, or let the spawn continously check the enemy reference.

rich adder
#

think they said if reaches certain Y pos not timer

timber tide
#

oh, yeah can do that too inside of enemy ;p

tribal axle
#

can i do that in a movement script or should i create a new one for an enemy?

rich adder
#

if enemy has no script make one, or do 1 loop thru all spawned ones

#

either works

#

many update loops but surely position check shouldn't be too much overhead

timber tide
#

You can make a single enemy class with AI/movement combined if that's workable for you.

tribal axle
#

thank you guys!

#

ill be back soon

timber tide
#

would then require the enemy to have some bidirectional reference back to the manager though

rich adder
#

read that many individual Update loops can cause unecessary overhead

#

haven't profiled fully yet n be able to tell much diff

sage mirage
#

Hey, guys! I have a problem. I want to play my background music of my main menu scene continuously where I do but not to multiple scenes only when moving and loading one single scene to play it continuously how to do that?

sage mirage
#

Yeah ddol is for playing it continuously I want to make it for a specific scene for a single one

rich adder
#

ohh i misread that sry

sage mirage
#

I made a script DontDestroyOnLoad() and there I have it

rich adder
#

so you want to check if you switched to specific scene?

#

nd play certain track?

wintry quarry
sage mirage
#

For example, I am pressing play button to load main game scene and for that method where I am loading that scene to make that DestroyOnLoad and to destroy that game object that my background music of main menu is attached to?

#

Here I have DontDestroyOnLoad script:

{ 

    // We are playing main menu music continuously from one scene to another!
    private void Awake()
    {
        GameObject[] musicObject = GameObject.FindGameObjectsWithTag("MainMenuBackgroundMusic");
        if (musicObject.Length > 1)
        {
            Destroy(this.gameObject);
        }

        else
        {
            DontDestroyOnLoad(this.gameObject);
        }
    }
}```

here is where I am loading options scene and main game scene:

 ```public void LoadOptionsScene()
 {
     StartCoroutine(LoadOptionsSceneAfterDelay());
     Debug.Log("Options scene is being loaded!");
 }

 IEnumerator LoadOptionsSceneAfterDelay()
 {
     yield return new WaitForSeconds(optionsButtonDelay);
     SceneManager.LoadScene("OptionsScene");
     Debug.Log("Options Button is pressed after a delay!");
 }


 public void LoadMainGameScene()
 {
     StartCoroutine(LoadMainGameAfterDelay());       
 }


 IEnumerator LoadMainGameAfterDelay()
 {
     yield return new WaitForSeconds(playButtonDelay);
     SceneManager.LoadScene("MainScene");
     Debug.Log("Play Button is pressed after a delay!");
 }```
rich adder
#

also why is this class called DontDestroyOnLoad lol

sage mirage
# rich adder im trying to understand , if its playing main menu music and u hop in game scene...

What I am doing in DontDestroyOnload script is that I am playing background music of my main menu scene when pressing options button and loading options scene but continously without starting at the beginning. For one reason, it does that for multiple scene for example when I am pressing play button I hear my main game music from background and also my main menu music that is not destroyed.

sage mirage
rich adder
#

but try not to name stuff after other unity names lol

sage mirage
#

Alright!

rich adder
sage mirage
rich adder
sage mirage
#

There is only one music game object that I have on that main menu scene

summer stump
sage mirage
#

Yes so how to destroy that instance I have created on my main game scene why it is playing main menu music for every scene I load from my main menu scene for example when I press play button or options where I want it to happen there only on that single scene and not to other scenes like main game scene.

rich adder
#

because thats what DDOL does

#

why did you use it then lol

summer stump
sage mirage
#

I want it only to play that music when transitioning between main menu scene and options scene. Not for every scene I load

rich adder
#

then do a scene name check

#

or something

#

destroy the whole object or stop whatever is playing

sage mirage
#

So, can I use somethign like SceneAsset like it says for that?

#

public SceneAsset nameofscene?

rich adder
#

there is an event on loaded scene

sage mirage
#

oh ok

rich adder
#

it gives you which scene you switched to

sage mirage
#

I can use that onloaded scene when I am interacting with my play button to load the main scene?

rich adder
#

i dont use the built in method

#

your DontDestroyOnLoad class should be called AudioManager or something

#

very confusing name

buoyant knot
#

you probably shouldn’t call a class DontDestroyOnLoad

#

that would be extremely confusing

#

I’m just going to !code

eternal falconBOT
buoyant knot
#

i just have this feeling that it was necessary

reef anvil
#

my intended behavior is for interaction to open a ui panel (PanelImage), which it does. when the ui panel is opened, i want mouselook and movement deactivated, which this code does.

now, what i want to happen is for the button that is on the ui panel to not only close the ui panel (which it does) but also to restore mouselook and movement. however, since "PanelImage.SetActive (true)" obviously isnt a bool... how would i check if the panel image is currently open?

#

if that makes any sense

#

so to oversimplify, what i want to add to my code is the ability to check if a game object is enabled or disabled, and create an if statement based on this

#

googling hasnt gotten me very far so im asking in here where i can give and receive more context :p

wintry quarry
#

they mean somewhat different things

nimble sorrel
#

would OnTriggerEnter still work if the trigger suddenly appears (such as through being inactive then suddenly active), rather than the object moving into the collider conventionally?

wintry quarry
#

of course

rich adder
wintry quarry
#

Same for the MouseLook

#

kinda wasteful and silly to use a GameObject reference there

buoyant knot
reef anvil
wintry quarry
#

sure, it's just a tip

#

adds safety in the inspector too - since you can only drag the correct objects in

reef anvil
#

i luckily dont need much in the way of optimization since this is gonna be a very small "game"

rich adder
reef anvil
#

(its not really a game, its a virtual gallery so its more of a walking sim)

reef anvil
#

a super janky workaround with a bunch of absurdly named structs

#

this is a lot better lmao

wintry quarry
reef anvil
#

my plans still include a lot of silly unoptimized things for the ui but it shouldnt matter

reef anvil
#

and the ui panel now works!

runic basalt
#

Does anyone know why the Update function in my script is getting hit 1 time when I disable the script in the Start function? Does disabling not occur immediately?

reef anvil
#

okay yeah no i need a better way to do it than the gameobject idea @wintry quarry

rich adder
#

Update can run before sometimes iirc

reef anvil
#

i moved the script and not only did it do this but i now cant drag the gameobjects back in

wintry quarry
reef anvil
#

into another folder

wintry quarry
#

Why?

#

Which folder?

reef anvil
#

it was just sitting in assets rather than the scripts folder

wintry quarry
#

ok - moving the script won't do anything

wintry quarry
#

look at your actual object in the scene

#

it won't have changed

runic basalt
# rich adder Update can run before sometimes iirc

I'm fairly certain update can't run before start, and if it can, it's not because the order of my debug statements shows the start one first and then the update. I'm just not sure why update is even being hit when I've disabled the script in the start function.

reef anvil
polar acorn
reef anvil
#

alright, i shall be back when i run into my next major roadblock

runic basalt
runic basalt
rich adder
#

DestroyImmediate should only be Unity editor

#

disabling a gameobject in start I didnt understand the end goal 😛

runic basalt
# rich adder What exactly are you trying to accomplish

I'm simply trying to disable this script in Start under certain circumstances. It's for vr, if there is a vr headset connected it doesn't disable, if not, then it does get disabled. I'm sifting through all our vr stuff at work and it's a mess left by a coworker. Not sure how this issues hasn't presented itself previously as it seems pretty clear that Update will run 1 time based on the execution order.

rich adder
#

eg if(thing == null) return;

runic basalt
# rich adder ohh did you try awake ? also dont you have a defensive condition in update so i...

I did not, I have just been debugging, haven't changed anything yet because this script is an absolute mess and the whole thing feels like a balancing Jenga tower ready to tip at any second. lol. Trying to make sure I fully understand what's going on before making any changes. And yea, you'd think we'd have a defensive condition but no, unfortunately we don't. lol. Might be the easiest quick fix for this though from the looks of it.

rich adder
fast oracle
#
    {
        foreach (SawSpawner SawSpawner in sawSpawners)
        {
            if (SawSpawner.isFinished)
            {
                continue;
            }
            return;

        }
        Debug.Log("win");
    }```
runic basalt
fast oracle
#

There was aout to be but I think I found an anwser

runic basalt
#

Ok, just a recommendation, make that function return a bool and then you can do return SawSpawner.isFinished. Much cleaner and more useful.

wintry quarry
#

They want to know if they're all finished

#
return sawSpawners.All(ss => ss.isFinished);```
runic basalt
#

Yea just realized that when I said that. lol.

queen adder
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EndRedirect : MonoBehaviour
{
    public GameObject EndState;

    public void Start()
    {
       EndState.SetActive(false);
    }

    public void vis()
    {
       EndState.SetActive(true);
    }
}

I'm just trying to activate an image part of my UI (a "you won" image popup essentially) and because it is set to inactive (I think) the image cannot be set active again and returns null. Any suggestions?

wintry quarry
#

Are you getting an error or something?

#

What's the issue?

queen adder
wintry quarry
queen adder
#

EndState.SetActive(true);

wintry quarry
#

Ok so EndState is null - my guess is you're calling the vis function on a different instance of EndRedirect than the one you screenshotted

#

on that other instance, EndState is not assigned

#

Most likely since we don't also see an error in Start, you're calling it on a prefab (unless you hid it in the screenshot)

queen adder
#

I'm calling vis from two other scripts, one for the main controller and one for a counter for convenience.

wintry quarry
#

you probably have it pointing at a prefab or something

#

or just a different instance in the scene

queen adder
#

I was having issues with referring to this script at all without it being static, I likely flubbed somewhere in trying to get rid of those errors.

wintry quarry
#

yeah you are referencing a prefab

#

(likely)

queen adder
#

I'm literally just trying to pull a
if ( i > 3)
{
otherscript.function();
}

wintry quarry
#

doesn't matter what you're trying to do

#

you have the wrong otherscript reference

queen adder
#

Sorry i'm just trying to clarify for context.

#

How would I reference the script without pointing to a prefab?

polar acorn
#

Which object are you trying to reference

queen adder
#

A UI image element on my canvas.

wintry quarry
#

anyway i gtg

polar acorn
queen adder
#

I am dragging from my hierarchy directly, not from a prefab folder.

It's just an image that I set to inactive immediately on the canvas and then try to reactivate when one of the end states is reached. It's always in the hierarchy, just inactive (I think that's what you meant).

polar acorn
#

Okay, so if both objects are in the scene together outside play mode just drag in the object into the inspector on the other script

queen adder
polar acorn
queen adder
#

Yes, it does.

polar acorn
#

In every EndRedirect script?

queen adder
#

EndRedirect is only a component of my Canvas and is referenced by my player script and a counter script, it's only attached in that one place. Should I be attaching it to the player object and count object as well?

queen adder
#

The canvas?

polar acorn
#

The EndRedirect component

reef anvil
#

as promised, i am back with my next roadblock

queen adder
#

EndRedirect is just a script component of the canvas, I'm sorry if I'm misunderstanding.

polar acorn
reef anvil
#

i got my first plaque object (Plaque 0, first image) to work and display text on my Plaque Text UI element. put in my next plaque object (Plaque 1, second image) expecting it to show that text when interacted with, but indeed, it shows the text from Plaque 0. why?

#

will provide more info if needed

queen adder
#

I have to take a break for a moment, I'll get back to give more info when I can.

reef anvil
#

nvm found the issue

#

issue wasnt with the code 🤦‍♀️

buoyant knot
#

it was a random checkbox, wasn’t it?

reef anvil
#

no, it was that, while i did write that second script, since i just duplicated the object, it still had the first script connected to it 😭

#

so until i find a better solution (which there certainly is), its a new, nearly identical script for each new plaque

#

very placeholder

#

in fact i am numbering the images and their associated plaques starting with 0 in case i need to put them in an array at some point so the numbering doesnt get confusing

dense root
#

What am I doing wrong with the logical operator here?

else if (japaneseEmulator.Substring(japaneseEmulator.Length - 2) == "zi" || "ji")
{
    japaneseEmulator = "じ";
}
#

It's saying I can't use or operator on a string?

wintry quarry
wintry quarry
#

it doesn't know how to do true || "ji" for example

#

bool || string doesn't make sense

dense root
#

Oh I see

fast oracle
#

Is there a way to do foreach but without the last item

onyx blaze
#

Hello, guys
I'm using a ScrollRect
My question is: How can I roll this rect to put my selected object in the screen when I control with arrows?

buoyant knot
wintry quarry
fast oracle
#

so I I can't do foreach

polar acorn
fast oracle
#

I want each minus the last one

#

For loop it is

buoyant knot
#

foreach just takes in an IEnumerable

polar acorn
fast oracle
#

True ig

#

thanks!

timber tide
fast oracle
#

is there a way to get the last item in an index? in Python you can just do -1

rich adder
#

.Last()

onyx blaze
fast oracle
onyx blaze
rich adder
#

you just need to add the namespace

#

I think there is a shortcut for last ^1 or something

#

forgot how rn

fast oracle
rich adder
#

but its overkill , I think you can do [^1]

fast oracle
#

ohhh you HAVE TO DO using System.Linq;

wintry quarry
#

no

#

don't use Last

#

use sawList[^1]

#

Last will iterate over the whole array (possibly)

rich adder
#

yeah myb about that suggestion I been in LINQ mode the past hours and forgot the quick array one lmao

short hazel
#

Always prefer ranges and indices over LINQ for array operations

#

arr[a..b], arr[^n], etc.

fast oracle
short hazel
#

Unity version too old :/

#

Can't use them

rich adder
#

dang

#

I guess just do sawList[sawList.length -1]

wintry quarry
#

yep pretty sure it compiles the same

fast oracle
timber tide
rich adder
rich adder
#

iirc c# > 8

#

how old is your unity 2019? @fast oracle

#

oh nvm its not support in unity c# 8 ?

#

tf

eternal needle
rich adder
#

so I guess unity 2020 didn't support this but 2021 does? weird

autumn briar
#

Hi, how can I change an object's global rotation? I'm using transform.Rotate() but it deals with local rotation.

rich adder
slender nymph
rich adder
#

ohh ops lol

hearty gorge
#

can i use custom classes with the serialization API & using ScriptableObjects to save data?

timber tide
#

You can serialize scriptableobject IDs to a custom class

#

as JSON

hearty gorge
#

ultimately I want to use a ScriptableObject to save data from a custom editor screen I'm writing - someone earlier pointed me towards using things like new SerializedObject(), serializedTileSet.FindProperty("blah"), serializedTileSet.ApplyModifiedProperties(); - I assume to ensure it saves properly - but my ScriptableObject has a property that is public List<Tile> tiles and I don't see how to read/write a new tile instance to that list through ( i assume ) InsertArrayElementAtIndex and GetArrayElementAtIndex

hearty gorge
reef anvil
#

okay, im not gonna do the stupid thing i wanted to do for the plaque interaction scripts. instead, im gonna (try to) write a script that changes the text in my TMP text object depending on which object was used to activate the script?

#

because 55 plaques each with their own script that is 90% identical seems like a really stupid idea

#

question is, (how) would a check for which object was interacted with work..?

hearty gorge
#

What does .SetUnderlyingValue() do? Is this a bad idea?

#

tbh at this point it might just be easier if I store an entirely different state object as JSON as a string property on the ScriptableObject i'm using to store state?

reef anvil
#

would i be able to simply drop in a check for which game object was interacted with?

#

does such a check even exist if the same script is shared between different game objects?

hearty gorge
reef anvil
#

how would i go about doing that

hearty gorge
#

iirc on the base of your class just have a property like public plaqueText { get; set; }, then replace your plaqueText.text = "some text" with plaqueText.text = plaqueText

visual delta
#

How do I change scenes when my timer hits zero?

#

one sec

hearty gorge
#

then when you open the items inspector there will be a text box per item that uses your script that you can write the text into

reef anvil
rich adder
hearty gorge
timber tide
hearty gorge
#

I originally was going to save as JSON anyway but read a ScriptableObject is the more "unity" way of doing it?

visual delta
rich adder
eternal falconBOT
reef anvil
regal scaffold
#

Hey everyone! I am having an issue with this project for class. I have "projectiles" that are supposed to knock a life off of the player. I have the script and everything set up but for some reason my projectiles just push my player and not knock a life off the player. I have debugging and all of the codes work but the life removal part never happens. Is there something I am missing like a checkbox or anything?

visual delta
#

I sent the code

timber tide
rich adder
regal scaffold
#

this is the code I have now for the projectiles

visual delta
#

I dont know how to do it correctly ig i just joined today :/

#

ill figure it out!

regal scaffold
rich adder
#

I shown you how

reef anvil
visual delta
#

ok no need to be rude

#

i didnt see your message

swift crag
#

you've been linked to the bot message

#

it tells you how to share your code.

reef anvil
#

found a solution, [TextArea(#,#)]

#

aaaand it works like a charm! thank you, @hearty gorge!

swift crag
#

the TextArea attribute is just used to give you more space in the inspector

reef anvil
#

for some reason it didnt before that and it does with it, so im not going to question the gods

swift crag
#

show me the line?

#

maybe it also makes Unity serialize the field if it wasn't otherwise going to be serialized

#

e.g.

#
[TextArea(5, 10)] string foo;
reef anvil
#

i used get, set before instead

swift crag
#

Ah, that's quite different

reef anvil
#

replaced it with serializefield, also didnt do it

#

textarea made it show up though

#

textarea is way neater for my particular usecase anyway

swift crag
#

i just had a look; [TextArea] does not cause the field to be serialized

#

only being public or being marked with [SerializeField] does that

reef anvil
#

its public

swift crag
#

Perhaps Unity didn't reload, or you had a compile error and it didn't actually update

reef anvil
#

its a public string, no idea why it didnt show up before

regal scaffold
#

also whenever each tower that shoots the projectile shoots 2 of them it seems I get a missing reference exception error. I cant figure out why which sucks and I am not sure how to keep them spawning every few seconds until the player collects all 20 items I've placed for this project

swift crag
#

well, look at the exception!

#

where is it coming from?

#

when you click on an error in the console, you'll see a whole stack trace in the bottom half of the console

#

you'll want to click on the topmost line that's part of your code

regal scaffold
#

It seems it is coming from the Tower code I made to shoot the projectiles. with my Instantiate line. is it cool if I post that line here since its only one or should I post a hastebin link?

swift crag
#

show just that line, yeah

#

Short blobs of code can just go in here directly

regal scaffold
#

Instantiate(projectilePrefab, transform.position, Quaternion.identity);

swift crag
#

And what exception are you getting?

#

oh right, missing reference

#

Okay, so projectilePrefab is probably null

#

I would make sure that you're referencing a prefab, and not just an instance of a prefab in the scene

#

Go to the inspector for the tower and click on the bullet reference

#

If it highlights something in the hierarchy, that's your problem

regal scaffold
#

Okay, I am new to unity should I drop the projectiles object I made into the assets folder to make sure it wont disappear I only have it in the hierarchy rn

swift crag
#

Correct.

#

Right now, you don't have a prefab at all

#

You just have an object in a scene.

#

When you drag something from the hierarchy into the Project window, you create a prefab from that object.

#

A prefab is an asset that can be referenced as a GameObject, or as any component on the prefab's root object

swift crag
#

once that bullet is destroyed, you can no longer make copies, because it's gone

regal scaffold
#

Holy crap that seemed to work!! Thats one of many issues down pat lol.

swift crag
#

So, make a prefab, then drag the prefab asset into the field

#

Just referencing the instance in the scene (even though it's now a prefab instance) wouldn't help

regal scaffold
#

I just cant tell why in the world my projectiles when it hits the player it just pushes them instead of knocking off a life

swift crag
#

sounds like your collision code isn't working right

#

I would start here

regal scaffold
#

I guess a good question now... I dont have any prefabs except projectiles I just made facepalmpicard does player need to be a prefab too...

swift crag
#

Create prefabs when you need many copies of something

#

If you aren't spawning new copies of the player, you don't have to make the player a prefab

#

You might still want to do that if the player appears in several scenes, though.

#

(so, "many copies" could mean "one copy in each scene" 🙂 )

regal scaffold
#

Thankfully for this project I only need it on one scene lol. But that is extremely good to know

#

I realized that I am currently using OnTriggerEnter. Would that not be the same as collision overall? I just need it take away a life point if it touches the player.

solemn fractal
#

Hey guys, if I have a prefab that I am spawning a lot of it using instantiate, how do I delete all of those summoned using that prefab at the same time? Like if I trow a bomb that kill all at the same time and they need to be destroyed? Is there a way to do this?

ivory bobcat
#

Maintain a list of them and call destroy on every element

solemn fractal
#

😦 only that way ?

#

or Find method and destroy each with this tag?

ivory bobcat
#

Or have them under one parent and destroy the parent..

#

I would probably never use Find unless absolutely necessary or if performance isn't a factor

polar acorn
#

But if it's a bomb or something you'd probably want to check an area, right? So an OverlapSphereAll

solemn fractal
#

its not a bomb was just an example

#

its like when appear the boos everyone else dessapears

jaunty estuary
#

Hi, I'm currently trying to set up my development environment for making a classlib for a unity game on Linux in vscodium but I'm struggling a lot to understand what exactly I need.
Currently I am trying to use msbuild "project.csproj" to just compile my project.cs into a .dll to test if anything works at all.
I'm on arch and installed mono-msbuild and mono-tools not understanding which I actually need.
Excuse my lack of context and/or coherence rn, I've been at it for a bit and lost track of all the things I tried. If crucial information is missing, I'd be happy to provide it.

visual delta
#

Can i please have help on how to add a scene change when the timer hits zero

visual delta
#

Thank you

sterile radish
#

how would i set the value of a timer equal to a slider?

polar acorn
#

Depends on what you mean by "timer". You can get the value of a slider pretty easily but what does "setting the value of a timer" mean

sterile radish
#

sorry i meant cooldown*, currently i have a sort of timer system where whenever the timer meets the cooldown an object spawns and the timer is set back to zero. however, i want to cooldown to be interactable so i want to find a way to make a slider that changes the cooldown depending on its value

nocturne violet
#

Hi guys, i'm currently thinking on making a player controller using rigidbody. But the problem is I don't know any good ways to make the player move in a constant speed kinda like transform.translate(). Does anybody know any good methods?

#

I tried velocity, but it ends up to stick on walls when you walk in to them

ivory bobcat
nocturne violet
#

oh

ivory bobcat
#

Be warn though that Rigidbody component simulates real physics and not necessarily game (fake) physics.

nocturne violet
#

i see

#

thank you

hollow axle
#

I'm trying to make a zoom in/out function in my script. I've watched a tutorial about it and I realize the camera in my game doesn't work properly unlike in the tutorial. Changing the value of Size should zoom in/out. However, in my case changing the value doesn't do jack shi. Why is that? Did I do something wrong from the start?

slender nymph
#

you are looking at canvas objects, likely on a screen space canvas. so naturally the orthographic size of your camera will not affect the size they appear. it will affect how you see world space objects though. try throwing some sprite renderers in the scene and you'll notice it is actually working

hollow axle
#

you're right! I still don't get how this works. So how should I make the zoom in/out function?

#

Should I add Spirit Renderer to the Ball objects?

static cedar
#

You're doing stuff on canvas from the looks of it. UnityChanThink

#

You don't really move the camera to move the canvas, or zoom in or out.

#

The canvas stuff is meant for UI.

#

If those balls aren't meant for the ui, put it outside of the Canvas game object. And yes, use sprite renderer since Image is meant for ui too.

solemn fractal
#

hey guys to create a perfect 1d20 dice like in RPG.. i know that if I put like random.rage(1,21) if random is 10 do something its not the best way.. any ideas?

eternal needle
solemn fractal
#

its the best way?

eternal needle
solemn fractal
#

oh. i dont know I understood hahaha.. here is another try:

#

What is the best way to create a 1d20 dice with code. And create an IF statment saying that IF the dice rolls lets say 10 I will do a critical damage. Is that the best way? or what is the best way to do it?

#
private int random = Random.Range(1, 21);
if (random == 10) {
  critical damage
} ```
#

is this a good way?

viral hemlock
#

Quick question how can I count up a variable

#

In seconds

eternal needle
summer stump
eternal needle
# viral hemlock In seconds

add time.deltaTime or Time.unscaledDeltaTime every frame. depends on if you are changing the timescale ever and you want this in terms of in game time or real life time

solemn fractal
eternal needle
raven trench
#

if someone could link me with something or help me out with this that'd be great, i have an audiosource on my object and im trying to play it when my if statement happens but i just cant find a good tutorial on how to actually set that part up

swift crag
#

i'm not sure what "that part" would be

#

actually triggering the audio source?

raven trench
#

yeah mb thats what i meant im bad at wordin it

swift crag
#

Play() will make it start playing the audio clip that's been assigned to it

#

There is also PlayOneShot

#

You give it an AudioClip and the audio source plays it.

#

This is useful for sound effects.

raven trench
#

so the clip is whatever i put into the source and the source is automatically whatever the component is on right

swift crag
#

when I say "audio source", I mean the component named "Audio Source"

#

in this case, I've attached an audio source to an object, and assigned an audio clip named "swoosh 5" to it

raven trench
#

alr i see i see

swift crag
#

You can drag this component, or the object it's attached to, into an AudioSource field

#
public class MyComponent : MonoBehaviour {
  public AudioSource myAudioSource;

  public void DoSomething() {
    myAudioSource.Play();
  }
}
#

if I dragged that audio source into the myAudioSource field of this component, and then called DoSomething on it, the audio source would play that "swoosh 5" sound

raven trench
#

ok so if i wanted it to play on something as that thing got destroyed it would stop the audio aswell right?

swift crag
#

Yes. Destroying the audio source would stop the sound

raven trench
#

ok i think i might switch the source to be the particle system thats created cuz its supposed to be a destroy sound

#

and then make it run on start

swift crag
#

That'd be a good idea.

#

It would also be simpler

#

Note that this method isn't called on a specific AudioSource

#

It's a static method

#

It winds up creating an audio source, making it play the sound, and then destroying it

raven trench
#

i see i see

#

i think ima go with the particle system thing but ill keep that in mind when i do more audio stuff later

#

if its on start i dont need a script right?

swift crag
#

but I think just putting the audio source on the explosion prefab would be the best

#

right

#

you'd just have a particle system and an audio source on the same object

#

and both would be set to play automatically

#

You would need to do something to destroy the object eventually, though.

#

But you could just do something like

#
var explosionFX = Instantiate(explosionPrefab);
Destroy(explosionFX.gameObject, 5f);
#

this would destroy it after 5 seconds

raven trench
#

nah nah the way i have it set up

#

it instantiates the particle system when it gets destroyed, and the particle system auto destroys itself when its done playing so it would auto destroy the sound aswell

#

cuz the particles come from something shattering

swift crag
#

ah, I couldn't remember if that destroyed just the particle system

#

or if it destroyed the entire object

#

looks like it's the latter

raven trench
#

yeah ima test it out rq

#

alr it works 🙏

#

ty for the assistance

swift crag
#

np!

queen adder
#

Not exactly code related but didn't know where else... How do I make the camera not zoom in and out like in the screenshots?

#

I remember there was a solution to this but I can't seem to find it

swift crag
#

your game view is changing in size

#

perhaps pick a fixed aspect ratio

abstract finch
#

Is there a difference between transform.localRotation.eulerAngles; and transform.localeulerAngles?

chilly vigil
#

does anyone know how to update this code for my fortnite battle royale game

summer stump
eternal falconBOT
summer stump
twin bolt
#

Question, i have a script that is placed on every floor title, that plays a sound when a item hits it, only issue is that if a item with a rigidbody is already on the ground, then it will play the sound in the beginning. Would it be bad to start a 100 couroutines for each floor tile with the script on it, so that it doesnt play the sound at the very beginning. If so, how should i do this?

gaunt ice
#

Why you have to start 100 coroutines…

chilly vigil
twin bolt
gaunt ice
#

Is there any script/different on tag on the objects that can be placed on top of the tiles?
I mean filter the objects on top of the rigidbody

twin bolt
gaunt ice
#

Separate the object by whether they are placed by player, via tag or layer or other ways then you wont start the coroutine because of the objects on top of tiles at very beginning

summer stump
chilly vigil
#

https://hastebin.com/share/bowuhucaku.csharp i meant this that is the oringial one i am tried to recreate, lmk me know if you need my copy of it

vocal sail
#

Asking a question: How to play a video trailer on game start when pressing a game start button and transfer to another scene when video ends?

#

Codes on Unity documentation is kinda out dated and isn't usable

swift crag
#

what documentation are you looking at..?

#

I'm not sure how it'd be "out dated"

vocal sail
#

yes I was looking at that page but the use of var keyword failed

swift crag
#

well, I can assure you that var continues to exist

#

We cannot see your screen. Show us your code.

vocal sail
#

eyy not var is camera.AddComponent<UnityEngine.Video.VideoPlayer>();

summer stump
chilly vigil
vocal sail
swift crag
#

your code does not match the example

#

Camera.AddComponent is attempting to find a static method on the Camera class called AddComponent

#

which doesn't exist

vocal sail
#

yes when pressed the gamestart button will trigger the GameStart() method

swift crag
#

that has nothing to do with what I said

vocal sail
swift crag
#

no it does not

#

it does this:

#
        GameObject camera = GameObject.Find("Main Camera");
        var videoPlayer = camera.AddComponent<UnityEngine.Video.VideoPlayer>();
#

it finds a game object named "Main Camera", then adds a component to it

#

this is completely different

#

I would suggest just doing this:

Camera.main.gameObject.AddComponent<UnityEngine.Video.VideoPlayer>();
#

this will attach the video player component to whatever object the main camera is attached to

vocal sail
#

Appreciated

#

Yes it works, thanks

swift crag
#

usually, names that start with a capital letter are a type (like the Camera class)

#

and names that start with a lowercase letter are a variable (like that camera variable that the example code made)

summer stump
#

That is all still valid and normal code.
What do you want updated?

#

I guess you could do a Decal on the ground, but the ZoneWall would still be needed, because a decal is just a 2d projection on a surface

glad pecan
#

How can i know where the garbage come from in garbage collector?

#

I turned on deep profile but found nothing

summer stump
#

Let me look for a sec longer

#

PlayerTargetController does a bit

#

Sorry, having a hard time seeing which line is with the numbers on my phone haha.
You can see the numbers in GC Alloc though.

tiny leaf
#

if I have a coroutine field and I assign a new coroutine to it, will the old one that was assigned to it still be running

verbal dome
#

You can turn on GC Alloc callstacks

#

Under the Call Stacks dropdown

glad pecan
tiny leaf
#

ok thx

formal escarp
#

I have a weird problem im not sure how to fix it. I have implemented code so every time i take a step a stepsound comes out. It sometimes comes out, it sometimes dont. Not sure if the problem itself is the code or the colission of my player.

#

Fixed it. Drank a big class of cola and fixed it.

spare mountain
pulsar lodge
#

Would anyone be able to help look at some code with me? Im having some inheritence issue when trying to display a HUD, The sprites are loading correctly, and the speed/action bar is, but name/stats are all pulling from the same object instead of different objects

sacred yoke
#

Im having trouble with the game animator interfering with .Rotate and transformations any advice?

pulsar lodge
#

this is roughly what my code looks like, the 3rd and 4th screenshots are the same script, theres more, but its just a bunch of get/sets.

#

Heres my HUD object

tacit flame
#

How can i fix my Camera's Panning so it pan's how my character pans

#

I have it set up so WASD is normal movement & Q and E Pan Character's forward direction left and right

teal viper
eternal falconBOT
teal viper
tacit flame
#

Camera Follow Script:


public class CameraFollow : MonoBehaviour
{
    public Transform target; // The target to follow (your character)
    public float smoothSpeed = 0.125f; // Adjust this for smoother movement

    private Vector3 offset; // Offset from the target

    void Start()
    {
        // Calculate the initial offset
        offset = transform.position - target.position;
    }

    void LateUpdate()
    {
        // Apply the player's rotation to the camera
        transform.rotation = target.rotation;

        // Calculate the desired position based on the offset
        Vector3 desiredPosition = target.position + offset;

        // Smoothly move the camera to the desired position
        transform.position = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
    }
}```
teal viper
tacit flame
#

Thought i had it targeting the player

teal viper
#

It copies the rotation of the player, but rotates around itself.

#

Orbiting around an object is position change + rotation

#

Honestly, camera controls can get pretty complex. I'd just advice using cinemachine

teal viper
# tacit flame cinemachine?

Yes. It's a package providing all kinds of camera controllers and stuff.

I had another look at your code. If you want to fix it, you'll need to calculate the offset every update from the target orientation.

tacit flame
#

k i found it

teal viper
pulsar lodge
#

this is what is in my PlayerHUD component

#

I tried creating a PlayerHUD for each player, but i got the same results.

#

when putting it into the battlesystem

teal viper
#

You didn't share the BattleHUD script did you?

pulsar lodge
#

i might not have, let me do that real quick if i didnt

teal viper
#

Ok, so looking at this code, does nothing ring a bell to you?😬

public void setData(Character character)
    {
        char1Name.text = character.Base.Name;
        char2Name.text = character.Base.Name;
        char3Name.text = character.Base.Name;
        char4Name.text = character.Base.Name;
        char1HP.text = "HP "+  character.currentHP + "/" + character.MaxHealth;
        char2HP.text = "HP " + character.currentHP + "/" + character.MaxHealth;
        char3HP.text = "HP " + character.currentHP + "/" + character.MaxHealth;
        char4HP.text = "HP " + character.currentHP + "/" + character.MaxHealth;
        char1Mana.text = "Mana " + character.currentMana + "/" + character.MaxMana;
        char2Mana.text = "Mana " + character.currentMana + "/" + character.MaxMana;
        char3Mana.text = "Mana " + character.currentMana + "/" + character.MaxMana;
        char4Mana.text = "Mana " + character.currentMana + "/" + character.MaxMana;
        char1Speed.setSpeed((float)character.Speed);
        char2Speed.setSpeed((float)character.Speed);
        char3Speed.setSpeed((float)character.Speed);
        char4Speed.setSpeed((float)character.Speed);
    }
sacred yoke
#

It is in a late update but the animator keeps resetting all transformations done by rotate or prevents rotation

#

any other possible issues?

pulsar lodge
#

Well, i thought the character object was referenced individually with the the Battle System SetUpBattle method, when i'm calling playerUnit2.Setup() etc

teal viper
pulsar lodge
#

and where im doing Player2HUD.SetData(Playerunit2.Character)

sacred yoke
#

Is that not what the lateupdate does updating every after the animator?

glad pecan
sacred yoke
#

I dont think it is working unless Im doing something worng

teal viper
glad pecan
#

HI, anyone know what’s Object.op_Equality() in profiler? It take 4611.33ms to execute and caused huge lag spike

teal viper
# glad pecan

Checks object equality probably. I think the issue is not with the call, but with how many times it's called.

teal viper
glad pecan
#

ReferenceEquals() this one?

sacred yoke
#

oh ok ty for the advice

teal viper
umbral bough
#

Hi, I wrote a simple Dune-like terrain generation.
It is based off of a closed sprite shape and it works semi-fine.
There is a huge issue tho.
I can't determine exactly when, but it seems that if a player is going too fast? or a camera is quite distant from the shape it just disappears for some time.
It also happened that the fill and collider were gone but outline was still there but that was only once.
I disabled c# tessellation since that seemed to cause the issue even more often but I can't figure out why it's happening rn.
Here's the code I wrote and thanks in advance!

pulsar lodge
#

Clearly i've messed something up along the route.

umbral bough
teal viper
glad pecan
#

What would you look for in this case?

teal viper
glad pecan
#

Yeah it comes from the UI. This is not my code so I am quite lost..

pulsar lodge
#

I mean, i get that its passing the same object's name into each of the text fields. Do you think this would be fixed by making my Character object a list and store them, that way i can reference Character[0].base.Name?

teal viper
glad pecan
#

I see. Appreciate your help!

teal viper
teal viper
teal viper
umbral bough
sacred yoke
#

Here is a small video of the problem and a picture of the currnet script. There is no code beyond the comments to note, and this still doesnt work. Is there any other things that could be causing a problem? The video showccases the attempt to rotate the hip and the small jiggle it does when I press D and A

ivory bobcat
sacred yoke
#

watch the footage very closely the foot is jiggling

#

I believe the animator is constantly resetting the transformation

ivory bobcat
#

The feet wiggled a bit. Is that what you're trying to rotate?

summer stump
#

What object is this script actually on?

#

And ARE you animating the transform?

sacred yoke
#

It's on the very root of the model

#

and I dont think I have an animation attached to the transform. It's just the .rotate function

languid spire
sacred yoke
#

Does this seem about right?

eternal needle
sacred yoke
#

It comes from the input readed from the input action component provided by Unity.

eternal needle
# sacred yoke It comes from the input readed from the input action component provided by Unity...

share !code in the format described under. Also this still doesnt really tell me what previousMovementInput is. Like what range of values do you get? Your rotation code doesnt seem to be using the previous rotation of the player and im not sure that this input is storing large enough values so that your xRotation could be 0 to 360. So what i said above might be true, that you get an object that'll fluctuate between some values due to Time.deltaTime

eternal falconBOT
craggy ledge
#

Hello, i was converting a movement script with the built-in character controller from this https://docs.unity3d.com/ScriptReference/CharacterController.Move.html , to a state machine from here https://www.youtube.com/watch?v=qsIiFsddGV4 . There are 2 things that i want to ask

  1. When it transitions to the jump state, it immediately go back to idle state, does anyone know where the problem is and how to fix it? i think there is a split second it is still grounded so it goes back to idle state but i don't know how to fix it without changing the abstract class
  2. There is a delay when i want to jump using the state machine version compared to the non-state machine version where it is all smooth, does anyone know what is happening?

the code is here https://gdl.space/desotukixa.m

thank you 🙏

sacred yoke
#

https://hatebin.com/alqeekcqkd Here is the code for the script, and an image of the input reader I used. I believe it gets a Vector2 everytime an arrow key is pressed.

runic lotus
#

hey guys i have some c# scripts that do certain actions (one for whiteboard so you can draw on it, one for marker so it can draw, etc..), how can i do this in visual scripting? is there a way I can call these same scripts in there ?

upper igloo
#

How do people write class-based state machines without enums?

eternal needle
# upper igloo How do people write class-based state machines without enums?

A simple example is just declaring an abstract class that has an enter, update, and exit method. Then any class inheriting from this abstract class implements functionality. For example in a MoveState, you can pass in the transform, then on update (your own update, not monobehaviour's) you move the object.
The state machine would store which state is currently active and call update on it (whether you choose that to be every frame or whatever fixed duration). State machine would handle changing states, while calling the enter/exit method.

upper igloo
#

Would I need to pass the state machine as context into each state to change states? Or is there a way I could trigger a signal across some event bus to have it change state instead?

eternal needle
#

a state machine could be as simple as

public class StateMachine
{
    StateBase currentState;

    public void Initialize(StateBase state)
    {
        currentState = state;
        currentState.EnterState();
    }

    public void UpdateState()
    {
        currentState.UpdateState();
    }

    public void ChangeState(StateBase state)
    {
        currentState.ExitState();
        currentState = state;
        currentState.EnterState();
    }
}
upper igloo
#

Right, but how would each state tell the state machine to change states?

#

That's my issue sadcat idk where to go from here in implementation without passing the whole state machine through each state (which i don't want to do)

eternal needle
# upper igloo Right, but how would each state tell the state machine to change states?

another separate class could be interacting with this. I mean this definitely could work if you do pass in the state machine itself but i feel it starts to get weird when states themselves handle transitions. If you had an IdleState, MoveState, and AttackState, all the states would have to know about each other. It gets weird if you have 2 enemies with different behaviour, lets say one goes idle -> move -> attack. Another doesnt move, it just goes from Idle -> Attack. Now you need to write some pretty awkward code in the IdleState rather than having an Enemy script that reuses the same Idle code

teal viper
upper igloo
eternal needle
# upper igloo how would you handle state transitions? the way I was thinking seems like gobble...

what im doing is also probably gobbledegook, i need to make mine better because making enemies with an unknown amount of AttackStates is weird. The state machine i posted above is a simplifed version of what i use
Right now I have an Enemy script (should probably rename that), which is monobehaviour. On awake it creates the idle state, move state, attack state, and state machine. then initializes state machine to idle. if anything it can see is in range, itll move to them (with unity AI). If anything is in attack range itll swap to the attack state and try using the attack. If nothings in range then just be idle.

#

there are definitely more advanced implementations online, but I just keep mine simple for the time being

upper igloo
#

so either way, all states will have some class know all other states

umbral bough
eternal needle
upper igloo
teal viper
#

Try pausing and looking at the camera position when the issue occurs. What position does it have?

solemn fractal
#

hey guys if in start method from a class I run a random.range(1, 10) I can get that value from another class right? because for me isnt working so far

#

even tho the number is being randomized in the first class first and after it i try to fetch that info but I get no value

fossil drum
#

Completely depends on your implementation

gaunt ice
#

Are you trying to get the value in start or awake?

solemn fractal
#

tried both

ivory bobcat
#

Is it the correct reference?

gaunt ice
#

Initial the value in awake and get it in start

solemn fractal
#

I am working now but will try to post here a better explanation of how is the code in a moment

solemn fractal
hallow badger
#

I just want start working out my idea in me head to a game. Now that is hard part how put think of head in to il. Where do you need to start if you new to this. Because i want to start like 100 things at the same time.

solemn fractal
fossil drum
hallow badger
#

like a mind map?

gaunt ice
#

is the start and awake same script?

solemn fractal
#

yes

gaunt ice
#

then you can do all the stuffs in awake

solemn fractal
#

As I am intantiating the class that contains the random generator first and than using an if on the other class to check should work I cant understand.

#

will try all on awake

#

still doesnt work.. well I will try more later and see what I can get.. thank you for the help tho 😄

gaunt ice
#

use comparetag instead of ==

solemn fractal
#

I will, thank you. everyone say that. never had a prob with that.. but I will start using compare instead of ==

#

for sure must be better as everyone say that to me

#

hahahah

gaunt ice
#

== is error prone, but the comparetag will throw if you mis type the tag

solemn fractal
#

hmm ok ok got it.

ivory bobcat
#

Did the value change? Your critical mechanic that works with accessing the value might be what's faulty.

solemn fractal
#

de value is 0 on log

#

The critical mechanic work for the number change and color but on the enemy class where i check for the hit and double the damage doesnt work there the value of random is 0

ivory bobcat
#

Did you assign it zero again?

solemn fractal
#

yes, but after the bullet is deleted and all the checks are made.. it never goes into the if.. so its normal to be 0. So its arriving as a null and turning into 0.. must be the order of somethibng prob..

#

I am working now but will try later better, dont want to bother u guys more now because I can really test it further enough.. but will do it later and if the issue persist after some hours trying I will come here back. Thank you a lot for your time.-

keen dew
#

My guess is that you're referencing the prefab again

ivory bobcat
#

Why use _overhead when you can use other's critical random?

#

Call get component on other and use it's component instances' value instead of _overhead's value.

solemn fractal
solemn fractal
#

no my bad wait

ivory bobcat
solemn fractal
#

I will check, sorry for the confusion guys.. I gathered all the info and will test it during lunch time soon. thank youy a lot

ivory bobcat
#

You'd simply need to call get component to acquire the component script instance and access the public field

solemn fractal
#

I will try this way now, I have a small break.

#

like that gives me object reference not set as an istance of object

gaunt ice
#

you should call getcomponent on the argument passed into the onTriggerXXXX callback

solemn fractal
#

ahh ok.. its wierd sometimes something like that cs [SerializeField] private Bullet _bullet; and on inspector I drag the prefab and it appear a script icon.. sometimes I do the same and instead appears the prefab icon..

#

Bullet here just as example

teal viper
#

If you drag in a prefab, it would be a prefab, if you drag an object in the scene, it would be an object in the scene.🤷‍♂️

ivory bobcat
#

With runtime instances (not in the hierarchy in the Editor), you'll need to acquire their references after they're available

#

They become available after they're instantiated

#

And that's per instance you'll need to do this with

solemn fractal
#

or I am just to dumb, that is more likely to be.

ivory bobcat
teal viper
#

It depends on what(where from) you're dragging it in. Objects in the scene outside of play mode can have a prefab icon if they are linked to a prefab. They're are still objects in the scene though.

ivory bobcat
#

No collision, no need to ever call get component - Start will always fire but collision might not ever happen.

solemn fractal
#

done 2 tests.. and that is what I get and the one with script is the one I am using to get the random value

teal viper
#

Instead of paying attention to the icon, pay attention to what you're dragging and where.

solemn fractal
ivory bobcat
#

And with referencing from the player, the instance will require you to have multiple variables if more than one bullet exists at any given moment.

teal viper
solemn fractal
# teal viper One is a gameObject, the other is a component 🤷‍♂️

yeah but none works anyways. at least not for what I want.. I will need to think maybe other way to make that critical work.. this one is cracking my mind.. so hard sometimes to think on the logic to create simple stuff.. but as always I will get there . it will just take me more time.. today after work i will have my mind free and try again or try another logic and if I cant i post here again. thank you all

teal viper
ivory bobcat
#

Likely neither of them are referring to the instantiated bullet and it's instance of the component/script.

#

The prefab doesn't call Awake or Start so the value acquired will likely be zero

solemn fractal
#

ok i managed to do it.. prob not a good way.. but sometimes i think about crazy stuff that go around and around.. at least I did it.. even tho prob it is done in a hiorrible way

#

when I spawn the number I get the component and I add the value of the random to a variable and use that variable to check

#

here

#

and worked

ivory bobcat
#

Above head is already a game object so you don't need to acquire it's game object from the gameObject property

solemn fractal
#

I am sure my code is a mess about everything and there are 1000 ways better to do it but I am a beginner.. at least I am managing to do stuff even being a horrible mess code

solemn fractal
velvet herald
#

How do I rotate an object but not at its center, but by using a specific pivot point? Does that have to be coded

#

Or is there a setting for it

solemn fractal
#

hahahahaha.... ok got it.. when I did a bootcamp 2 yeras ago.. they said to me.. there is no good prog there is prog that makes progs that work.. so he said that no matter how mess or bad .. ugly is the code if its working and with performance

ruby python
#

Mornin' all,

Just curious if anyone knew how, or could point my in the right direction to get my little enemies to move in a 'hopping' motion please? (Image attached for clarity). Ideally not using a rigidbody

ivory bobcat
#

Assuming you were asking a code question - this is the beginner code channel

ivory bobcat
ruby python
ivory bobcat
#
y = abs(sin(x * rad))``` pseudo code
ruby python
tidal sundial
#

Hey guys, i have this issue from morning and it would be amazing if someone could help. When I try to make second box collider on my object, I can’t see edit collider button, first one is working with no problem, no error in console or any script but I can’t reach the second edit collider button even if I delete or restart the box collider

gaunt ice
#

if you are in window system, you can use the prt sc key to screen shot

teal viper
verbal dome
teal viper
verbal dome
#

Imo even worse practice is using extra gameobjects when it is not needed

#

But yes sometimes it is good to separate colliders if your code requires it

teal viper
#

I guess it's a preference thing. But then again, compound colliders are a thing for a reason.

teal viper
# tidal sundial Why?

Well, for once, because they don't seem to let you edit the collider.🤷‍♂️

tidal sundial
teal viper
#

With 2 or more colliders on the object

tidal sundial
#

To be honest I m new, just trying to learn after work few months, and the guy I was watching in tutorial teached me like this at the beginning, I've been doing this ever since I watched it. Code in flow you probably know

shadow cave
#

Hey guys, I am modifying my gun script to deal damage to players. I need to reference the player object to get the health script in the Gun script. How do I do this?

tidal sundial
teal viper
gaunt ice
#

your gun directly references to the health script in player

#

eg```cs
[SerializeField]private ScriptName instance;

teal viper
tidal sundial
#

Oh, okay, thanks 😊

wintry quarry
tidal sundial
gaunt ice
#

he said the gun will damage the player (shooter?)
maybe i misunderstood he said players

wispy wharf
#

Hi Guys, why i can .text in my code ?

#

im making a slitch counter, and i want it to be visible

keen dew
#

Apparently the type of txtscore is object and not what it's supposed to be

silk night
oblique gale
#

why does naming your script "gameManager" changes your icon into this? unlike the other scripts

wispy wharf
#

@silk night

swift crag
swift crag
#

it's also...internal for some reason

silk night
swift crag
#

why did you write it like this?

oblique gale
swift crag
#

compare this to your other variables

wispy wharf
swift crag
silk night
#

you have written it 😄

swift crag
#

I put the really "high level" game state into it

#

for example, here's part of my Game Controller class

silk night
#

My gamemanager usually hold the references to managers that do other stuff, one "singleton" that you can access everything from

Unless im working in an ECS pattern like right now

swift crag
#

When you click "new game", you ask the game controller to load the default progression data, load the main game scene, additively load the starting area, and then spawn a player

#

The game controller is responsible for detecting switches in game state and notifying other objects about it

#

So when you switch from the Loading state to the Gameplay state, it tells the interface controller that it needs to start showing gameplay-related canvases

#

In this game, my GameController is a singleton that lives in DontDestroyOnLoad

silk night
swift crag
#

It is created when the game wakes up and lives until the game quits

#

also, check this out

#
using UnityEngine;

public abstract class PrefabSingleton<T> : MonoBehaviour where T : PrefabSingleton<T>
{
    private static T _instance;
    public static T Instance 
    {
        get
        {
            if (_instance == null)
            {
                _instance = Instantiate(Resources.Load<T>("PrefabSingletons/" + typeof(T).Name));
            }

            return _instance;
        }
    }
}
#

handy way to "bootstrap" your game

wispy wharf
lethal depot
#

HIi , i was following one of the tutorials from youtube about player movement using cinemachine and character controller , after following it step by step i'm having trouble in player movement according to the camera , as you can see in the video when i'm pressing w to move player into camera direction it moves there successfully but when i change the camera angle to go backwards(against the edge of the plane) it still goes into forward direction(which here is the edge of plane) , pressing s key to go against edge works but the head of the player is still in the wrong direction , i don't know if it has to something with player direction or character controller or camera Here's the script attached to player public class ThirdPersonPlayerController : MonoBehaviour
{
public CharacterController controller;
public Transform cam;

public float speed = 6f;

public float turnSmoothTime = 0.1f;
float turnSmoothVelocity;
void Update()
{

    float horizontal = Input.GetAxisRaw("Horizontal");
    float vertical = Input.GetAxisRaw("Vertical");
    Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;

    if(direction.magnitude>=0.1f)
    {
        float targetAngle=Mathf.Atan2(direction.x, direction.z)*Mathf.Rad2Deg+cam.eulerAngles.y;
        float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity,turnSmoothTime);
        transform.rotation = Quaternion.Euler(0f, angle, 0f);


        controller.Move(direction * speed * Time.deltaTime);

    }
}

}

eternal falconBOT
swift crag
#

for that much, use a paste site

#

Just glancing at that, though, I would suggest not doing the triginometry yourself

#

Unity can handle all of this math for you

wispy wharf
#

@silk night last help please, i fixed last error, but now.

silk night
#

you need to drag the text you want to change into the field in the inspector

rich adder
#

damm you still didn't solve this from yesterday? @wispy wharf

#

you outta go through some c# basics

wispy wharf
#

@rich adder There always have to be annoying people like you, I come from other languages, and @silk night is very willing to help everyone here, if you don't want to help, just try not to get in the way and not demotivate those who are starting out, ok? as the room already says, beginner.

silk night
rich adder
# wispy wharf <@968604165150507078> There always have to be annoying people like you, I come f...

Mate I was trying to help you yesterday , Telling someone to go through the basic courses is not something you should take offense. Its a legitamate suggestion.
when code editor was telling you something isn't found or exist/ that is part of knowing the basics which is accessing other fields in other classes 🤷‍♂️ also understanding why the editor is telling you what its telling you

wispy wharf
#

Thank you all.

rare rain
#

https://www.youtube.com/watch?v=YUIohCXt_pc

i was following this tutorial for making a tooltip (with slight modifications) and ever since i've changed my canvas resolution im having trouble to position the tooltip correctly.

i've set my canvas's reference resolution to 640x360 and for some reason the UI transform.position of the UI element i hover on is given in very small numbers (something like (8, 0.2) despite being towards the middle of the screen). when i convert that to screen coordinates i get coordinates to the scale of my screen's resolution which is 1920x1080. how can i correctly convert those coordinates to the canvas coordinates in order to show the tooltip correctly?

swift crag
#

Is your canvas set to "Screen Space - Camera" or "World"?

rich adder
#

Ah codemonkey vid

#

do you have to download his "Utilities" in this one too

rich adder
#

also SS inspectors for yeah canvas and such

#

dude said write clean code, uses transform.find

#

using hierarchy names in code 👎

rare rain
# swift crag Is your canvas set to "Screen Space - Camera" or "World"?

1st image is canvas, second is object in UI heirarchy im testing on.

code for tooltip:

        public void ShowTooltip(string text, Vector3 position)
        {
            gameObject.SetActive(true);
            SetText(text);
            rectTransform.anchoredPosition = (position / canvasRectTransform.localScale.x) + new Vector3(1, 0, 0);
        }

position is the tranform.position i give from the object itself

rich adder
#

but might

rare rain
#

orthographic

oblique gale
#

I'm trying to do an encapsulation for the game stats, but I'm getting this error. I don't understand what's the problem

rich adder
#

so you can't use something that isn't there

formal escarp
#

Hey guys, anyone here knows how to make it so when i click on something (with my raycast) a sounds plays?

rich adder
rich adder
#

you cut off the lines

#

none of these are the Start method

#

so its prob wrong script

oblique gale
formal escarp
#

i can send it here if you wanna check it out.

rich adder
oblique gale
#

how?

rich adder
#

oh wait its above

#

im blind

#

so does this script have GameManager script on the gameobject ?

oblique gale
#

yep

#

oh wait

rare rain
#

is it gameManager or GameManager?

oblique gale
#

I found my error XD

rich adder
#

a copy ?

oblique gale
formal escarp
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ControlJugador : MonoBehaviour
{
    public float rapidezdesplazamiento = 12.0f;
    public Camera camaraPrimeraPersona;
    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
    }


    void Update()
    {
        float movimientoAdelanteAtras = Input.GetAxis("Vertical") * rapidezdesplazamiento;
        float movimientoCostados = Input.GetAxis("Horizontal") * rapidezdesplazamiento;

        movimientoAdelanteAtras *= Time.deltaTime;
        movimientoCostados *= Time.deltaTime;

        transform.Translate(movimientoCostados, 0, movimientoAdelanteAtras);

        if (Input.GetKeyDown("escape"))
        {
            Cursor.lockState = CursorLockMode.None;
        }
        if (Input.GetMouseButtonDown(0))
        {
            Debug.Log("hagoclick");
            Ray ray = camaraPrimeraPersona.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
            RaycastHit hit;
            if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, 50))
            {
                Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * 50, Color.green);
            }
            if ((Physics.Raycast(ray, out hit) == true) && (hit.distance < 5) && hit.collider.tag == "Enemigo")
            {

                GameObject objetoTocado = GameObject.Find(hit.transform.name);
                Enemigo scriptObjetoTocado = (Enemigo)objetoTocado.GetComponent(typeof(Enemigo));
                if (scriptObjetoTocado != null)
                {
                    scriptObjetoTocado.Recibirdaño();
                }
            }
        }
    }
}

oblique gale
#

I forgot to place an ADT XD

formal escarp
#

oop

rich adder
#

btw try to avoid GetComponent and use Inspector serialization instead

oblique gale
rich adder
#

just drag component in the inspector

#

there is almost never a need for GetComponent for init

oblique gale
rich adder
#

just causes hitches and headaches because you never know if its assigned or not by quick glance

formal escarp
oblique gale
rich adder
#

which part confuses you? where to add it or ?

formal escarp
#

I never did a play on raycast.

rich adder
#

I mean you already doing other stuff in Raycast, playing sound is not that much different
depend where your sound source is from

zealous bramble
#

пон

formal escarp
#

My best guess would be in line 48? and maybe with an "if"?

rich adder
formal escarp
#

Audio Source i think?

#

no wait. is that wrong?

rich adder
#

No I mean what FX you trying to play exactly

formal escarp
#

I apologize, i dont know what that means.

rich adder
#

like a shoot sound, a hit sound ?

formal escarp
#

oh

#

like a interact.

#

like, when you interact and the player says something.

autumn tusk
#

i dont understand why this cam function isnt working

rich adder
autumn tusk
#

does cam not exist anymore in my version of unity?

rich adder
#

therefore it cannot find it

oblique gale
autumn tusk
#

oh wait

#

nvm

rich adder
#

GetComponent looks for the script ON This script's object

#

if you don't specify where to look

oblique gale
rich adder
#

tell me which line is interaction

#

if this is doing other things than interacting like shooting then you should make a separate script just for interact

formal escarp
rich adder
eternal falconBOT
rich adder
#

GameObject objetoTocado = GameObject.Find(hit.transform.name);

#

this is like wildly not needed

#

you already have hit.gameObject

#

no need for expensive .FInd

formal escarp
#

Really?

rich adder
#

yes really

#

hit returns all the information of the collider it hit

#

you're looking for same gameobject by name on the gameobject you hit

formal escarp
#

when i do delete the GameObject objetoTocado line the code breaks tho D:

rich adder
#

because you deleted objetoTocado then it cant use it

#

nvm you dont even use it anywher

formal escarp
#

it should end up looking like this right?

#

wait let me send it

rich adder
#

oh wait

formal escarp
#

💀

rich adder
#

(Enemigo)objetoTocado.GetComponent(typeof(Enemigo)); why lol

#

delete this , send link please

rich adder
#

is annoying to scroll to a discord message just to read a line

formal escarp
#

Like that?

rich adder
#

yes thx

rich adder
rich adder
formal escarp
#

That´s bad?

rich adder
#

all unecessary

#

yes

formal escarp
#

oh.

rich adder
#

if you already need to look for the component then check for that directly

#

the component is like the tag but better

#

Enemigo is a component

#

if you want that specifically then the tag is redundant

formal escarp
#

Game objects = Component?

rich adder
#

no

#

components = scripts

#

not all scripts = components

formal escarp
#

oh alright

rich adder
#

Enemigo is not a game object but a type

formal escarp
#

I think im getting it now

rich adder
#

in unity any monobehavior is a component

formal escarp
#

okay

rich adder
#

ok so now you see what you can do ? back to the Audio Problem

swift crag
#

Game objects have components.

formal escarp
#

maybe a void with collision enter?

swift crag
#

that's what you see in the inspector when you click on an object

wintry quarry
rich adder
swift crag
#

void is the return type of your method, which means it returns nothing

formal escarp
swift crag
#
int GivesAnInt() { return 3; }
float GivesAFloat() { return 1.5f; }
void GivesNothing() { }
rich adder
#

so why would you use OnCollisionEnterlol

formal escarp
#

but i could lower the range of the raycast.

#

wait so wait.

#

New Script for the sound play.

rich adder
#

yes distance check should be INSIDE the physics

formal escarp
#

that first right?

rich adder
#

depends, if you just want audio source on your player then just reference that and just do .PlayOneShot or w/e

#

it depends where you want the sound to come from

formal escarp
#

Lets say, the player walks to a counter and the raycast hit the counter.

#

and sound comes out from player.

#

because it says something.

rich adder
#

yes so audiosource should just be on your player

#

for now

#

ideally you'd have a sound manager object

swift crag
#

if the player is making the sound, then it sounds pretty reasonable for the audio source to be on the player

rich adder
#

[SerializeField] private AudioSource soundPlayer

#

ideally in separate script if you want to have SerializeField] private Audioclip interactSound

formal escarp
#

I have 2 sounds in my game, one being a static object which repeats the sound always, and a sound that is like footsteeps and is on the player.

rich adder
#

the more sounds you add the more fields you need

formal escarp
swift crag
#

don't get ahead of yourself, though

#

start by just detecting when you want to play a sound

#

you can worry about playing it once that works

#

put Debug.Log("Time to play a sound!"); in your code and then make sure that, when you walk into an object, you see that get printed to the console

rich adder
formal escarp
#

man

#

my brain sure is going to melt 💀

#

im going to try and do allthat and come back in a few hours.

rich adder
#

raycast interaction isn't an easy topic

formal escarp
#

or minutes not sure how much it should take me.

rich adder
#

dont change any code yet if it confuses you

formal escarp
rich adder
formal escarp
rich adder
#

wish my college had unity

modest dust
#

You guys have unity exams?

rich adder
#

we had windows XP

formal escarp
modest dust
#

I wish I had these too

formal escarp
#

wait b4 i go

#

then i make a new script to make it so it detects the hit im guessing and allat bc otherwise my code is going to be even more sloppy

#

and sloppy/messy code is no good.

rich adder
formal escarp
#

i have a theory that implies my college teacfher is an alcoholic.

#

but thats for another day.

rich adder
#

although you can make 1 raycast script that other scripts only receive event of a hit and then they process is their own way