#💻┃code-beginner

1 messages · Page 550 of 1

junior ivy
#

oh yeah I will play with 5k lines of code of internal unity class instead of injecting it as a property in my script and using it

white yew
floral estuary
#

but the larger context you were using it in was that they thought it was ridiculous to have to do extra to do something so simple. The response that you could write code to write that code that should be default for you doesn't hold up imo

#

the base argument here is people shouldn't have to reinvent the wheel by creating functionality that should be default

slender nymph
#

so because they wanted it to already exist means my response of saying that it is easy enough to implement yourself is invalid? next time i'll just say "that is impossible because it isn't in unity already"

slender nymph
signal mango
#

Writing something that just spits out a function that does GetComponent calls is definitely on the lower end of difficulty

floral estuary
#

okay well ANYWAYS

signal mango
#

And most of the finicky annoying things to handle probably won't pop up in most code

#

You could use the undocumented __internalAwake callback to avoid needing to call it yourself or preventing the user from defining an Awake callback as well

slender nymph
#

no no no, you see, it doesn't exist in unity. and someone else already made it. so suggesting to someone that they possibly learn to do it theirself "doesn't hold up"

white yew
#

Can we stop the belittlement of correctness going on in here? If unity doesn't have the feature, suggest it on their roadmap.

#

Thank you.

junior ivy
#

How to deal with custom global settings in c# that need to be set before other classes can use it?
For example let's say that I have MyScript.cs and GlobalConfig.cs and I need Awake method of GlobalConfig called before MyScript because it needs properties of GlobalConfig.

cosmic dagger
#

there is no way to determine the order Awake is called for a script . . .

slender nymph
#

technically you can set the script execution order, but if you're relying on that for your own code then you are gonna have a bad time

cosmic dagger
#

you can also set the script execution order, but it's not something you should rely on . . .

junior ivy
keen owl
junior ivy
#

I've heard that I can set execution order of .cs scripts in project settings but that' a horrible idea, I want to use dependencies out of the box

#

in Godot I have a entry point script where I can set everything and prepare my scene by hand
in Unity... I don't have such control (probably)

cosmic dagger
#

oh, you can also make GlobalSettings a singleton if only one instance of it needs to exist . . .

junior ivy
#

I already have a GlobalConfig singleton

keen owl
junior ivy
#

but I can't depend on it because I have no guarantee that its properties are initialized

keen owl
#

Then make sure they are?

cosmic dagger
junior ivy
#

I don't use Start at all 😉 I want to access GlobalConfig in Awake

cosmic dagger
#

you should never use values (data) from anothe inside of Awake as it's mainly used to intialize internal values on the script itself . . .

#

Start is used to grab external references and use their data because it will be initialized by then . . .

junior ivy
cosmic dagger
#

it ensures initialization order . . .

slender nymph
junior ivy
#

I won't set myVar to 1 for every script I have... instead I want to have a GlobalConfig with myVar and control this property in one place

cosmic dagger
junior ivy
#

potentially more than 100 different global options for my game that need to be set before any other script in awaken

cosmic dagger
slender nymph
#

again, why can you not just use Start to access that GlobalSettings object instead of Awake? why must this access happen in Awake

junior ivy
#

there are values that need to be initialized and Start is not for initialization afaik

keen owl
#

Then use OnEnable..

slender nymph
#

which is precisely why it is primarily used to access other objects

cosmic dagger
keen owl
#

I believe OnEnable is called before Awake

cosmic dagger
slender nymph
#

OnEnable is called after Awake, but it is not guaranteed to be called after another object's Awake

keen owl
#

It’s the first thing that gets called when the script is activated in your scene, no?

cosmic dagger
#

Awake is the first . . .

  • Awake
  • OnEnable
  • Reset
  • Start
keen owl
#

Ah, I see thanks for letting me know

junior ivy
#

hmmm okay so I should use Awake ONLY for local config and then if I want to depend on some class I use it in Start so that I'm sure my dependency is initialized

cosmic dagger
junior ivy
#

that makes sense

teal viper
cosmic dagger
slender nymph
keen owl
#

Yes, I didn’t look into the documentation you’re right

teal viper
cosmic dagger
teal viper
#

I'm not sure boxfriend would appreciate that lol

slender nymph
#

sometimes i forget that my username would normally autocorrect to that. i've been using it for more than a decade now so my phone has recognized it for a very long time. it is pretty funny to see it happen in the wild though

cosmic dagger
keen owl
cosmic dagger
#

@junior ivy also, i was asking to see the script to check what type of values you're setting. if it's just assigning simple data, you can use an SO and reference that for any script that needs it . . .

junior ivy
cosmic dagger
junior ivy
#

I've read it's called exactly in the first frame, not before

#

[internet]

teal viper
#

It does. But before the first frame is rendered.

#

There's no such thing as 0 frame

#

Awake is called in the first frame as well

verbal dome
#

It's even in the default template :p

cosmic dagger
#

0 frame does not exist. there has to be 1. it's just the start of it, so technically, before anything else . . .

verbal dome
#

I don't remember if Time.frameCount starts from 0 or 1 🤔 I think 0

junior ivy
#

if I imagine it in a low level, then it must be before the main loop so pretty much before the first frame

cosmic dagger
teal viper
cosmic dagger
#

either way, this doesn't affect you or what you're trying to do . . .

#

there are multiple ways to create an order of initialization that you can do. just pick one and test it . . .

keen owl
junior ivy
teal viper
teal viper
junior ivy
#

well I imagine that Awake is called for all scripts for all scenes that aren't even loaded

#

maybe bad assumption

teal viper
#

Indeed. How can it be called on something that doesn't even exist?

cosmic dagger
junior ivy
#

because I thought Awake it not related to scene loading or creation of base game objects

#

I thought awaking is a process called before all of that for all scripts in the project

teal viper
#

Nah. That would be crazy.

keen owl
#

Yes but you have to be in that scene. Imagine 300+ scenes running at once, you’ll crash lol

naive pawn
#

nothing is called on project scripts directly, they have to be added to gameobjects in scenes
when the scene exists, gameobjects exist, and then their components exist

#

awake is called on each component

cosmic dagger
junior ivy
#

well not running but you would only initialize them, shouldn't be a problem in less than few thousands (depending on what is really going on under the hood ofc)

naive pawn
#

it would have quite a bit of overhead

#

there's a ton of scripts just in UnityEngine

#

also this doesn't make sense within the context of OOP, so maybe you should brush up on that

cosmic dagger
#

none of this affects what they originally wanted to do. that was already answered. at this point, they (seem) to be grasping at issues or looking for inadequacies . . .

heavy knoll
#

Anyone know why my unity project sometimes gets stuck on reloading domain forever and i have to close it in task manager? I've had this happen twice so far and it sucks

cosmic dagger
#

ouch, that's not cool. are you waiting for many changes, or just simple code fixes?

heavy knoll
#

i had it happen for the first time at the very start after i updated my project to unity 6

#

and then it just happened again a second ago

cosmic dagger
#

has to be unity 6 issues. i would check if other people experience the same thing. maybe the forums?

heavy knoll
#

ok

#

yea I've never experienced anything like that on any of my projects before this so that's probably the issue

#

I currently just have one monobehaviour script that is on both of my ore node types and is being accessed by the playerhit script on my player which when hit by a raycast triggers the DamageNode() Method which lowers the health by the damage amount

#

once the health is 0 on the ore

#

it triggers a new method called DropItems() and spawns in how many items are set to spawn in the inspector which are just prefabs of a cube with a rigid body for now dragged into the inspector as a reference

#

not really sure if this is good or not, any feedback would be appreciated

teal viper
heavy knoll
teal viper
# heavy knoll How do I do that also is that something I have to do before it happens so if it ...

You'll need to learn how to use your ide debugger first. There are plenty of resources on that online.

Once you know how to work with it, just attach to the editor process and press the break all(pause) button. Then you can see the callstack of the current thread and switch between threads.

The details are too much to explain in discord. You'll need to learn it on your own. But feel free to ask if you have specific questions.

heavy knoll
teal viper
#

One advice I can give is:
Don't try to make a perfect system right away. You're developing this system for the sake of your project, not the other way around.
When you start working on a feature that the current implementation does not allow, think of how you can refactor/modify it such that this and other similar features would be implemented with ease.

#

Basically, this should be your workflow:
Feature required -> does the system allow for such a feature? -> if not, extend the implementation

Wrong approach:
??? -> how to make it more modular

heavy knoll
#

Ok thanks

feral eagle
#

quick and simple question
is it not posable to instantiate in a class variable. I might have asked this questions a couple of years ago I don't remember.

All one Example Code:

using UnityEngine;

//==== Main Class ====//
public class Example : MonoBehaviour
{
    [SerializeField]// Class Variable
    private ExampleClass exampleClass;

    [Serilised feld]
    private GameObject exampleObj;

    void Start()
    {
        if (exampleClass != null)
        {
            exampleClass.exampleObj = exampleObj;
            exampleClass.ExampleFunc();
        }
    }
}

//==== Variable Class ====//
[System.Serializable] // To allow customization in the Inspector
public class ExampleClass
{
    [SerializeField]
    private GameObject exampleObj;

    public void ExampleFunc()
    {
        Instantiate(exampleObj);
    }
}
cosmic dagger
astral falcon
cosmic dagger
#

also, it has nothing to do with calling it from a field (class variable), but from a C# class instead of a MonoBehaviour . . .

#

a C# class has no concept of Unity or where Instantiate came from . . .

feral eagle
#

Thank you @cosmic dagger You were right. It needed MonoBehaviour. I was worried that adding MonoBehaviour would not work or might break it, but that was exactly what it needed to work.

teal viper
feral eagle
astral falcon
#

And adding a monobehaviour should be treated as a component, so added not instantiated

languid spire
#

<@&502884371011731486>

ionic zephyr
#

In an RPG type game in order to show the different maps (cities,plains,castles) is it all done in the same scene but changing the tilemap or is it done in any other way?

lilac turtle
#

how do i change variables from one script in another?

#

on left click im casting a ray which can detect if it hit an enemy but when it hits i want it to change the enemy's health variable

strong wren
strong wren
lilac turtle
#

do i have to reference to them all..

#

is there a way to do it with tags?

strong wren
acoustic sequoia
#

how do i assign both of these to the same property? doesnt make sence
tmpColorTitle.fontStyle = FontStyles.Normal FontStyles.UpperCase;

loud topaz
#

maybe someone can help me: why are backfaces grey and not white? (no settings changed in the material). the faces turn as i click them.

teal viper
#

If you don't care about lighting, use an unlit shader and there would be no difference.

loud topaz
rough bough
#

how can I detect if my player collides with something?

rough bough
teal viper
#

It would fix the back faces, but it would cause the same problem for front faces.

real thunder
#

does Start() within monobehavior of a GameObject I just spawned on a frame runs at the same frame?

burnt vapor
real thunder
#

cool, thanks

willow rock
#

hi! i m with unity tests, for some reason i cant find a way to start it in my pacman, i think is because i cant instantiate it...

could i ask for some help? !code correctly please twt

#

i m trying in playmode rn

#

yeah, unit test are awful xp

burnt vapor
#

Also, a tiny !code snippet doesn't give any context share everything related please

eternal falconBOT
verbal dome
#

What are you testing, just curious

willow rock
#

i add the getcomponent in differentes elements

#

this is my setup for the test

#

i segmented ghost and pacman in two, i want to create the objects

#

this is a playtest of the ghost

verbal dome
#

What is the actual issue?

burnt vapor
eternal falconBOT
burnt vapor
#

Because right now the answer to "i just want to inicializate the elements in the unit test" is "just do it"

#

It should work fine. If it doesn't work then check if the code is executed at all

willow rock
#

heres the playtest, ghost and the createObject, which seems to me that it doesnt initialise

verbal dome
#

You are doing new Ghost() which is invalid

#

Ghost is a MonoBehaviour, you shouldn't use constructors with those

#

Nvm It's an array of Ghost[] 🤦‍♂️

willow rock
#

i m sharing the game manager too

#

unpopular - clamp

severe onyx
#

Trying to think of an elegant way to execute code when the value of an enum changes, with different functions called depending on what the value was changed to. Right now my best idea is just putting a big ol' switch into the setter. Is there a better way to do this?

burnt vapor
#

This is the proper way to notify of value changes

#

Alternatively, if the aim is just to notify of a single value or event, use the event pattern or UnityEvent

west radish
#

How should I decide whether to make a new class derive from MonoBehaviour or not?
For instance, my Garden tool has a component that defines the rectangle the garden exists inside.

There's no actual reason why that Rectangle component needs to derive from MonoBehaviour, but at the same time, theres no reason why it couldnt be a Mono class

burnt vapor
#

If it doesn't need that, you can go lower. For example, have it inherit from Behaviour or Component.

west radish
#

I could give my Rectangle class its own Update function, then when Garden updates I can call Rectangle.Update myself

burnt vapor
#

Perhaps you should also consider if your classes must be part of Unity's base classes anyway. If you don't use Unity features such as instantiating or otherwise hooking onto gameobjects, maybe you can make a basic class.

burnt vapor
rapid mountain
#

is an object data type good to use in general?

west radish
#

speed/optimisation isnt a concern

burnt vapor
#

Json related?

runic lance
#

the biggest differences are probably in performance and usage pattern
if everything inherits from MB (or similar) you're always going to have inherited fields that are possibly unused
for MBs you need to Instantiate and then setup the object somehow, with POCOs you have the constructor

frail wind
#

guy can anyone tell me the diffrent betwen
"GetComponent<Rigidbody>().linearVelocity = Vector3.up * jumpHight;"
and
"myRigidbody.velocity = Vector2.up * jumpHight"
i know it make player jump but what the diffrent?

runic lance
#

I personally enjoy decoupling everything I can from MBs

rapid mountain
runic lance
#

additionally MBs are bound to hierarchy lifetimes, POCOs not necessarily

burnt vapor
#

Generally you don't need object. If a method can return multiple values you should probably use a generic type with a generic constraint. If you have a variable that can represent multiple values, you should look into base classes

#

And if neither are applicable, object is also completely fine, but you should definitely do some pattern matching to determine the correct type.

west radish
#

its the layout of my Garden tool thats the issue.
Garden will be my MonoBehaviour and for all intents and purposes, Garden is the actual GameObject.
Then the Components are all used by the Garden to produce the final result.

#

As Garden is definitely a MB, that sort of removes the need for its components to also be MB

rapid mountain
cosmic dagger
frail wind
#

i also have other question. what is vector2 and vector3?

cosmic dagger
frail wind
#

i just type it and dont understand what it mean

cosmic dagger
eternal falconBOT
rapid mountain
burnt vapor
#

But unless you introduce variables that get a lot of boxing (like each frame), you probably should not worry about it

cosmic dagger
#

i'd question why you need to use object in the first place. the data type itself should suffice or T for generics . . .

rapid mountain
burnt vapor
#

Even better, if this is with Json for example you might even want to consider using JObject

#

This can be anything, doesn't need a base class, but also prevents boxing I believe?

cosmic dagger
burnt vapor
#

I think it still boxes, but it is more flexible over object

runic lance
#

boxing happens when you treat a value type as a reference type, like casting Vector3 to object

#

using a JObject to wrap a Vector3 will still create a reference type containing the value type, so no victory there

#

if you're only dealing with reference type there wont be boxing anyway

burnt vapor
#

Regardless you'd allocate the JObject anyway, so even if there was no boxing it made no difference

#

Still, a thinn to think of in terms of flexibility

stuck palm
#

if a parent is disabled, will that call ondisable on the children too?

cosmic dagger
#

time to open up unity . . .

swift crag
#

(even if enabled is still true)

stuck palm
#

I see, thanks

swift crag
#

annoyingly, this behavior of behaviours is not described clearly in the documentation

#

it's implied by the OnDisable example

obsidian dagger
#

Why is it telling me its wrong

#

Its literally the simplist line of code in history

wintry quarry
hexed terrace
#

because it's wrong 😄

wintry quarry
#

Compare your code to examples

obsidian dagger
wintry quarry
hexed terrace
#

google -> unity input.getkey -> read docs

wintry quarry
obsidian dagger
wintry quarry
#

Have you tried looking at example code?

obsidian dagger
#

Example code?

wintry quarry
obsidian dagger
#

Like from unity learn?

wintry quarry
#

any example of anyone using GetKey

#

from anywhere

obsidian dagger
#

Ah

#

Well im following a vid rn

wintry quarry
#

and look at what you did

#

they are completely different

#

Fix yours so it's like theirs

obsidian dagger
#

Oh wait

#

Im so dumb

wintry quarry
#

When you are programming you can't just write something that is "sorta similar", it needs to be exact.

obsidian dagger
#

Im so sorry i didn't notice the key code

wintry quarry
#

it's not just the KeyCode part

#

look at everything

obsidian dagger
#

Alright

wintry quarry
#

the parentheses, etc

obsidian dagger
#

Let me analyze everything again

tired hull
#

Hi im getting a few errors with my 2d space shooter game im trying to make im very new to coding for unity btw

wintry quarry
#

You need to configure it before you do anything else

#

!ide

eternal falconBOT
obsidian dagger
#

Why is it telling me its expecting a ";" but when i put it there it underlines the entire code, and what exactly does the ; do (why do we close lines with it) so i understand it for future reference

wintry quarry
obsidian dagger
#

Ah huh

wintry quarry
#

maybe you meant to write else if?

#

Again, pay closer attention to your tutorial

obsidian dagger
#

Oh

wintry quarry
#

Exactly

obsidian dagger
#

No wonder i do terribly at school

#

I have the attention span of a rock

swift crag
#

consider working on it

obsidian dagger
swift crag
#

Single-line statements are things like...

int x = 123;
Foo();
return 1;
#

you also have block statements:

{
  int x = 1;
  x += 1;
  x = 5;
}
#

An if statement runs the next statement only if the condition is true. You often use block statements so that you can do more than one thing!

obsidian dagger
#

gotchu thanks man

swift crag
#
if (foo)
  Foo();
else if (bar)
  Bar();
else
  Baz();

and

if (foo)
{
  Foo();
}
else if (bar)
{
  Bar();
}
else
{
  Baz();
}

are equivalent

trim moon
#

Hi guys i am begginer in unity and c#. Does anyone know how camera for third person in unity should look like, i have my code for camera and movement but i can't make camera rotate how i would like, if anyone can help i would be thankfull

tired hull
swift crag
#

Especially for a third person follow cam -- it has a "Third Person Follow" mode

swift crag
#

you sent screenshots of Visual Studio

wintry quarry
#

That's a different program

obsidian dagger
trim moon
swift crag
#

I don't know what "visual studio code desktop" is

wintry quarry
swift crag
#

You'd just add a Cinemachine camera and tell it "please follow the player"

swift crag
#

along with some parameters for how it should position itself

#

Check this out

trim moon
#

so do i delete my camera code?

swift crag
#

If you've never used Cinemachine before, make sure you install the 3.0 version

#

I dunno which one is the default right now

swift crag
tired hull
trim moon
#

ok thanks i will try it now and will tell you later if it works

#

there is third person aim camera, is that it?

wintry quarry
swift crag
#

Ah, but yeah -- that's what you want!

#

That'll be pre-configured

#

You'll want to make it target either the player's root (the object that holds every other player object) or maybe the player's chest bone (if it's human-shaped)

#

notice how mine targets an object called "Third Person Root"

#

which is just an empty object parented to my player object

trim moon
#

it is just a cube

#

you are doing God's work man btw this have helped me a lot i just need camera to follow mouse do i do it in code?

tired hull
viral comet
#

Can anybody help me? it says :

"'object' does not contain a definition for 'rotation' and no accessible extension method 'rotation' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)"

ivory bobcat
swift crag
#

Can you share the entire script? !code

eternal falconBOT
swift crag
#

use paste.ofcode from that bot message

ivory bobcat
viral comet
#

give me one moment

swift crag
#

(I'm guessing you have a field named transform higher up)

ivory bobcat
wintry quarry
ivory bobcat
viral comet
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerCam
{
    public float sensX;
    public float sensY;

    public Transform orientation;

    float xRotation;
    float yRotation;
    private object transform;

    private void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }
    private void Update()
    {
        //get mouse input
        float mouseX = Input.GetAxisRaw("X") * Time.deltaTime * sensX;
        float mouseY = Input.GetAxisRaw("Y") * Time.deltaTime * sensY;

        yRotation += mouseX;

        xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, -90f, 90f);

        // rotate cam and orientation
        transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);
        orientation.rotation = Quaternion.Euler(0, yRotation, 0);
    }
    
} ```
swift crag
#

this is short enough to just paste inline anyway

#

so yeah, there's your problem

#

You have declared a field named transform

#

its type is object, which is shorthand for System.Object

ivory bobcat
swift crag
#

That's the top-level type in C#.

#

It's very very vague!

tired hull
trim moon
# swift crag use paste.ofcode from that bot message

sorry if i am bohring to you fen i have added a script to my main camera so it moves with my cursor and it did not work, than i have added debug log to see it in console, and console detects that i am moving my mouse but screen does not move

ivory bobcat
#

And make your PlayerCam inherit MonoBehaviour

viral comet
#

now it gives me this

swift crag
swift crag
# viral comet

the other problem is that this isn't even a MonoBehaviour

#

notice how your class does not inherit from anything

#

You've got methods named Start() and Update(), so it sounds like you meant to inherit from MonoBehaviour

viral comet
#

holy shit, yall are so smart

swift crag
#

As-is, it's just a "plain old object"

trim moon
viral comet
#

thank you so much

swift crag
#

no prob (:

#

You can now attach PlayerCam to a game object, since it's now a component

swift crag
tired hull
#

is the devenv.exe supposed to be a conf file because thats the only one i can find

trim moon
swift crag
#

You use Cinemachine Cameras to tell it how to do that

#

Have a look at the documentation I linked earlier

ivory bobcat
swift crag
#

It'll explain how Cinemachine works

ivory bobcat
tired hull
obsidian dagger
#

How do you put a ≠ sign in c#? I dont have it on my keyboard and iirc there was a sign for it

ivory bobcat
#

Looks fine. If your ide isn't configured make sure you added the Unity workload when installing/modifying Visual Studio

#

If you run the Visual Studio installer again, it'll allow you to modify Visual Studio instead of installing.

obsidian dagger
viral comet
swift crag
viral comet
#

i just started coding last night, I only know the bare minimum

viral comet
swift crag
#

you're currently using the old Input Manager. You can see all of the axis definitions in the project settings

ivory bobcat
swift crag
viral comet
sonic plover
#

project settings

swift crag
#

open the Project Settings window (it's in the "Edit" menu in the menubar for me)

#

not to be confused with Preferences, which is for personal settings

tired hull
viral comet
ivory bobcat
#

After it's configured, you ought to get some red squiggly lines here if everything's working correctly

swift crag
viral comet
ivory bobcat
viral comet
#

sorry, i honestly have no idea what im doing lmao

ivory bobcat
#

It's definitely not configured atm.

#

After you've added the Unity workload, you may need to reboot Unity.

obsidian dagger
#

How'd you guys learn coding?

#

Im just following a tutorial i know what this and that does but i have no idea how to write code on my own

wintry quarry
obsidian dagger
#

Can you recommend me to somewhere where i can learn?

wintry quarry
#

It will make it a lot easier though

obsidian dagger
#

Ah

#

gotcha

obsidian dagger
wintry quarry
obsidian dagger
#

Alright

wintry quarry
#

on the phone you'd just be passively watching videos

#

which is less likely to "stick"

obsidian dagger
#

Yep true

tired hull
#

@ivory bobcat all the other errors are gone but im still getting this error

viral comet
#
using System.Collections.Generic;
using UnityEngine;

public class PlayerCam
{
    public float sensX;
    public float sensY;

    public Transform orientation;

    float xRotation;
    float yRotation;
    private object transform;

    private void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }
    private void Update()
    {
        //get mouse input
        float mouseX = Input.GetAxisRaw("X") * Time.deltaTime * sensX;
        float mouseY = Input.GetAxisRaw("Y") * Time.deltaTime * sensY;

        yRotation += mouseX;

        xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, -90f, 90f);

        // rotate cam and orientation
        transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);
        orientation.rotation = Quaternion.Euler(0, yRotation, 0);
    }
    
} 

Can somebody help me out? it says my input axis X is not setup?

#

urgent!

wintry quarry
#

You don't have an axis called "X"

#

I think you probably want "Mouse X", which is a predefined one?

You can see your input axes in Project Settings -> Input Manager.,

#

Also just FYI it is an error for you to be using Time.deltaTime here. it's going to make your looking around very jittery

swift crag
#

didn't I explain why "X" isn't a valid choice? :p

viral comet
swift crag
#

also, you still have private object transform; in there, and this still isn't a MonoBehaviour

viral comet
#

because im special

wintry quarry
viral comet
sharp echo
#

where i crate a class???

wintry quarry
eternal falconBOT
#

:teacher: Unity Learn ↗

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

sharp echo
swift crag
trim moon
#

i am allowed to add screen record?

viral comet
#

coding hurts my brain

swift crag
trim moon
swift crag
#

I'm talking to Christmas here, not you

trim moon
swift crag
#

You need to turn down the damping values

#

Higher values mean the camera moves and rotates more slowly

shadow rain
#

does anyone hav any idea y this isnt working?

wintry quarry
#

coroutines can only delay themselves

swift crag
#

otherwise the entire game would freeze

wintry quarry
#

You would have to put the next line inside the coroutine, and after the wait, if you want it to happen after the wait

shadow rain
#

ok

viral comet
#

what do i need to do to fix my problem. Do i need to switch "X Axis" with MouseX?

trim moon
swift crag
#

You need to use a valid axis name, such as:

"Horizontal"

#

I don't know how to explain it and more clearly than that

viral comet
#

ohhhhh

wintry quarry
viral comet
#

ohhh

#

shit

#

i comprehended it!

#

i got it now

swift crag
#

oh yes -- you want "Mouse X" here

#

"Horizontal" would be arrow keys

spare mountain
swift crag
#

yeah, I think you get both

quartz oyster
#

I have this, works fine but for some reason on mobile its not smooth at all, I tried upping the animationDuration but it still wasnt smooth

private IEnumerator MovePanel(RectTransform panelRect, Vector3 startPos, Vector3 endPos)
{
float timeElapsed = 0f;

while (timeElapsed < animationDuration)
{
    panelRect.anchoredPosition = Vector3.Lerp(startPos, endPos, timeElapsed / animationDuration);
    timeElapsed += Time.deltaTime;
    yield return null;
}

panelRect.anchoredPosition = endPos;

}

swift crag
#

I only use the new input system, so I'm pretty fuzzy on theo ld input manaegr

viral comet
#

SO instead of X i would put Horizontal?

spare mountain
swift crag
#

both are mapped

swift crag
wintry quarry
spare mountain
quartz oyster
#

StartCoroutine(MovePanel(rectTransform, rectTransform.anchoredPosition, openPosition));

#

On a button click

viral comet
#

im smart

flat sphinx
swift crag
#

unity would have to generate a source file based on your Input Manager settings

#

these aren't "hard-coded" into the engine

swift crag
viral comet
# swift crag note that things like "the Q key" **are** enums -- see `KeyCode`

SO IN THEORY, this should work?

using System.Collections.Generic;
using UnityEngine;

public class PlayerCam: MonoBehaviour
{
    public float sensX;
    public float sensY;

    public Transform orientation;

    float MouseXRotation;
    float yRotation;

    private void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }
    private void Update()
    {
        //get mouse input
        float MouseX = Input.GetAxisRaw("X") * Time.deltaTime * sensX;
        float mouseY = Input.GetAxisRaw("Y") * Time.deltaTime * sensY;

        yRotation += MouseX;

        MouseXRotation -= mouseY;
        MouseXRotation = Mathf.Clamp(MouseXRotation, -90f, 90f);

        // rotate cam and orientation
        transform.rotation = Quaternion.Euler(MouseXRotation, yRotation, 0);
        orientation.rotation = Quaternion.Euler(0, yRotation, 0);
    }
    
}

a

#

wrong msg reply

#

oh well

swift crag
#

You are still using the wrong axis name here

#

It doesn't matter what you name those variables

viral comet
#

fudge

swift crag
#

You really need to stop and use !learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

swift crag
#

it doesn't seem like you understand very much about C# at all -- which is fine, you're new

#

but you need to have a better handle on what's going on here

viral comet
#

you're right

quartz oyster
#

I have this, works fine but for some reason on mobile its not smooth at all, I tried upping the animationDuration but it still wasnt smooth, i call it like this : StartCoroutine(MovePanel(rectTransform, rectTransform.anchoredPosition, openPosition));
on a button click

private IEnumerator MovePanel(RectTransform panelRect, Vector3 startPos, Vector3 endPos)
{
float timeElapsed = 0f;

while (timeElapsed < animationDuration)
{
    panelRect.anchoredPosition = Vector3.Lerp(startPos, endPos, timeElapsed / animationDuration);
    timeElapsed += Time.deltaTime;
    yield return null;
}

panelRect.anchoredPosition = endPos;

}

static ice
#

helo

#

Why is it blurred out

#

I need to set it to other camera

#

for split screen

#

Please help about this man

#

anybodf7y

swift crag
#

That field is only there to show you the currently-live camera

#

You aren't meant to mess with it

#

See here.

static ice
#

thanks

#

bud

#

ok

toxic cloak
#

does anyone knows how to kill a specific tween if i set an id transform.DOScale(new Vector3(1.2f, 0.8f, 1.0f), moveDuration / 2).SetLoops(2, LoopType.Yoyo).SetId("StretchSqueeze");

rich adder
#

god I hate this doc you can't link specific sections

toxic cloak
languid spire
languid spire
#

so that should be stoppable, no?

rich adder
#

yeah you can stop the Tween that way too

dark laurel
#

@toxic cloak What's much easier (and less likely to .. be problematic if you have multiple items with the same tween string/int) is to just save a tween or sequence as a private member, and check if it's running when you need to kill/complete it

#

I have a pattern I use almost everywhere.. lemme dig it up and clean it up for ya

rich adder
#

yeah much better to store the Tween

#

strings are dirty

dark laurel
#

(and also just break if you have 2 components with the same id)

languid spire
#

Seems a much more logical way to do it

Tween tween = transform.DOScale(...);
...
tween.Kill();

updated

swift crag
#

Yes. Keep a reference -- much like with coroutines.

dark laurel
#

not necessarily - that just pauses it

rich adder
#

i think its still Kill

#

tween.Kill()

dark laurel
#

sometimes you want to kill it (when the object is deleted) and sometimes you wanna complete it (because you have something important to do OnComplete)

#

sec i'm trying to find my original doc.. i literally just have a printout nearby because I use this pattern that often and always forget it 😛

#
private Sequence _revealTween;
private void OnDisable() => StopTweens();

private void StopTweens()
{
    if (_revealTween?.IsActive() == true) _revealTween.Kill(); // or .Complete()
}
#

something like that

rich adder
#

the primetween docs is also so much better

dark laurel
#

rhys mentioned to me last year that he was gonna do a different tweening library - is that his?

#

nope, i'm not familiar with this guys

rich adder
#

not sure who that is lol

dark laurel
#

I'll have to check it out

rich adder
#

yeah its pretty good, someone else here suggested last time.

dark laurel
#

He's been less active in this discord since his product is nearly market ready, but it's rhys_vdw (not gonna ping him). Guys a genius.

dark laurel
#

I'm a bit too vested in the DOTween infrastructure.. i have a zillion (personal) utilities and libraries for it, so it's a bit much for me to change.. but I really would love to chat with 2020-Sharping to make a different decision

#

Like - why is there not a better "gravity" tween (instead of the weird-ish bounce tweens).. Or why isn't there any support for randomness in tweens.. or tween pooling.. etc

#

Or like, why do I need to either specify an ID or save a reference to kill/complete a tween instead of just letting the tween/sequence know when I create it what I want it to do when the GO dies/pauses/etc

languid spire
dark laurel
#

I'm too old to roll my own.. just barely smart enough to know that I'm not smart enough to do it

languid spire
#

too old? to me?

dark laurel
#

I mean, I do appreciate that DG.DT has a pretty robust api surface, and for all intents and purposes it works, but i hate the docs

#

haha

#

"too old" at heart.

#

I've written one thing that I've OSS'd and I'm proud of, and it's so tiny and niche that I can't imagine applying the same effort to a full tweening library.. i'm happy to slap my own shitty extensions on someone else's work and gripe about it unfairly :p

languid spire
#

man, youve had 4 years at least to write a tweening library, it takes literally weeks

dark laurel
#

You're right, I had nothing else to do in those 4 years :p

swift crag
#

Of course, you could also write a wrapper for it

languid spire
#

I gotta admit, the first time I needed a tweening library I looked at what was available and thought, wtf they are crap, so wrote my own

dark laurel
# toxic cloak Thanks

Here's a better example - sometimes I have what I call a "hit text" in my games - like numbers that float up in the UI from a position in the game.. but if the object underneath dies/disappears I want the hittext to continue to animate.. but if the LEVEL or something else ends, I want it to just delete instantly. Looks like this:

    public class HitText : BetterMonoBehaviour
    {
        private Sequence _seq;
        private bool _isTweenCompleteNormally = false;

        public void ShowAndDestroy(string text, float duration, Color startColor, Color endColor)
        {
            Vector2 newPos = new(transform.localPosition.x + NumberUtils.Next(MinX, MaxX), transform.localPosition.y + NumberUtils.Next(MinY, MaxY)); // random end position, based on some min/max constraints
            _seq = DOTween.Sequence();
            _seq.Insert(0, transform.DOLocalMove(newPos, duration));
            _seq.Insert(0, Text.DOColor(endColor, duration));
            ... more to it, but you get the idea ...
            _seq.AppendCallback(() => _isTweenCompleteNormally = true);
            _seq.OnComplete(() => Destroy(gameObject));
            _seq.Play();
        }

        private void OnDisable()
        {
            if (!_isTweenCompleteNormally)
            {
                _seq?.Kill();
                _isTweenCompleteNormally = false; // Set this to false so destroy doesn't try to destroy the GO again.
                Destroy(gameObject);
            }
        }
    }
#

this approach tracks the tween status directly with a bool (which gets "completed" at the end of the tween), and when the GO is disabled, if it's not complete, it just kills it

#

(normally "on complete" destroys it)

languid spire
#

should this not be true?
_isTweenCompleteNormally = false; // Set this to false so destroy doesn't try to destroy the GO again.
other wise the enclosing if is still true

dark laurel
#

hm - been a while since I actually looked at this closely, but I think if I didn't have that flag then destroying it in OnDisable led to problems if the GO was destroyed elsehow

#

(that object was already destroyed or marked for destruction)

#

like Destroy() doesn't actually destroy it, but instead calls OnDisable and then Destroy

#

I seem to recall that I had a pretty hard lock without the flag

#

in this case, we want the hit text just destroyed/stopped if the parent GO is disabled but not destroyed, actually, despite what I said above

pliant abyss
#

Transition from walk to idle and vice versa fires an extra time

cosmic shoal
#

guys when i buy an asset on unity asset store and try to open in unity editor the editor tell to read the EULA terms and agreed , i make this and when i try to do download the term message keep coming like a loop

#

how can i solve this?

wintry quarry
#

Reach out to the publisher

cosmic shoal
#

its not only this one every asset include the free ones having this issue

wintry quarry
#

Never seen that before.

#

Where are you seeing this? What region are you in?

hexed terrace
#

non-code question in a code chanel 🙄

No such thing happens for importing store assets

forest patio
#

hey, I have a problem with this spray and the problem is that when I hit a wall, the car flies through the walls using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CarController : MonoBehaviour {

public float MoveSpeed = 50;
public float MaxSpeed = 15;
public float Drag = 0.98f;
public float SteerAngle = 20;
public float Traction = 1;

    private Vector3 MoveForce;


void FixedUpdate() {

    
    MoveForce += transform.forward * MoveSpeed * Input.GetAxis("Vertical") * Time.deltaTime;
    transform.position += MoveForce * Time.deltaTime;

    
    float steerInput = Input.GetAxis("Horizontal");
    transform.Rotate(Vector3.up * steerInput * MoveForce.magnitude * SteerAngle * Time.deltaTime);

    
    MoveForce *= Drag;
    MoveForce = Vector3.ClampMagnitude(MoveForce, MaxSpeed);

    
    Debug.DrawRay(transform.position, MoveForce.normalized * 3);
    Debug.DrawRay(transform.position, transform.forward * 3, Color.blue);
    MoveForce = Vector3.Lerp(MoveForce.normalized, transform.forward, Traction * Time.deltaTime) * MoveForce.magnitude;
}

}

frosty hound
#

Your issue is that you're moving with transform.position which teleport its to the next position rather than using physics.

#

You need to use a rigidbody and take the MoveForce and apply it as actual force to the rigidbody.

forest patio
#

tehx

#

thx

#

but I have a stupid problem that I'm just starting with programming in C# and I don't really know how to do it

steep rose
tulip stag
#

hey! just a general beginner question— why is VS more recommended than VScode for unity?
Anything wrong with using VScode? Or should I stick with VS? I always used VS without questioning why just because I was told it's the right one for unity but after stepping away from unity dev and trying out other projects I'm left wondering what's so different about the two

wintry quarry
#

More consistent and less fragile

#

P.s. a lot of people use Rider too

green flame
#

Hello! Did I miss something in my code ? I would like my "mobs" follow the character. But my code do really nothing x)

        GameObject playerObj = GameObject.Find("Character");
        for (var i = 0; i < mobs.Count; i++) {
            float step = mobs[i].speed * Time.deltaTime;
            mobs[i].UnityGameObject.transform.position = Vector2.MoveTowards(mobs[i].UnityGameObject.transform.position, playerObj.transform.position, step);
        }

tulip stag
rocky canyon
# tulip stag hey! just a general beginner question— why is VS more recommended than VScode fo...

Rider is pretty solid.. it wasn't until recently that there was a free version you'd have to rely on early access versions... (also rider is pretty good at showing u optimizations in real-time)
the other ones can do this as well w/ AI plug-ins now-a-days

VSCode is my go-to IDE, for one I use certain plug-ins to code for embedded microprocessors.. And its lighter, and faster, and easier for me to jump around projects..

VSStudio is more of a full fledged IDE.. that VSCode can't directly replicate w/o the use of plugins. but nothing that can't be remedied

green flame
tulip stag
rocky canyon
#

💯 thats where I started

polar acorn
# green flame In the Update() ^^
  1. Don't use Find in update. Find the character once, and keep using that reference.
  2. Try logging step and mobs[i] to see if they're the values you expect (you might be referencing prefabs, or have accidentally set speed to 0)
  3. check if the mobs objects have a component that conflicts with teleportation like CharacterControllers
rocky canyon
#

you'll have the easiest transition into coding and unity w/ visualstudio imo

#

as u progress then you'll have the know-how and ur own preferences on where to go from ther

green flame
#

First 3 logs from here

polar acorn
#

Where do you set mobs? Are they objects in the scene, or prefabs?

green flame
#

mobs is a simple List that I use to store objects from my own class called "Mob"

#

In the UnityGameObject I store the associated GameObject and in speed a simple float

frigid sapphire
green flame
#

set at 4.0f

#

should I maybe add a certain component to my prefab used to spawn mobs ?

#

atm my class is really empty no conflict possible I think ^^

#

List<Mob> mobs; // -> In the top of the class

#

And somewhere when I want to create the mobs I have:

GameObject scePrefab = Resources.Load<GameObject>("alien1_prefab");
Instantiate(scePrefab, new Vector2(prefabX,prefabY), Quaternion.identity);
mobs.Add( new Mob("name", scePrefab));
#

My mob spawn properly ^^

cosmic dagger
#

You shouldn't need Resources to spawn a prefab. Assign the prefab to a variable and use that variable in Instantiate . . .

green flame
cosmic dagger
green flame
#

I created a script called "GameManager" which is used like an emulator to spawn enemies etc..

cosmic dagger
cosmic dagger
green flame
#

My current goal is not to do something perfect but just something working to learn a little bit Unity then yes I'm not focused on optimisation ^^

#

But thank you for your advices, I have changed some lines to optimize the thing (declaration on top..)

#

btw, my mobs is currently not moving x)

#

Logs are OK for me, the move code too I think ?

cosmic dagger
#

That's not an optimization. Typically, a script describes what it does and only pertains to one behaviour, hence, "mono" behaviour. I was trying to help steer you away from creating a monolithic GameManager class with everything inside of it . . .

green flame
#

Then is it better to create ScriptableObject?

cosmic dagger
rocky canyon
#

^ this is a fundamental type tid-bit

#

very important to learn

cosmic dagger
# green flame btw, my mobs is currently not moving x)

From my earlier response, you need to store the instantiated GameObject into a variable and pass that variable. Then you'll have the correct reference to the GameObject from the scene

Checkout Instantiate from the unity !docs. They have an example of this . . .

eternal falconBOT
green flame
#

Ok thanks guys I'll look at this 🙂 !

rocky canyon
# green flame Ok thanks guys I'll look at this 🙂 !
public class EnemySpawner : MonoBehaviour
{
    [SerializeField] private Enemy enemyPrefab;
    private Enemy thisSpawnedEnemy;

    void Start()
    {
        thisSpawnedEnemy = Instantiate(enemyPrefab, transform.position, Quaternion.identity);

        thisSpawnedEnemy.DoEnemyStuff(); // this reference is not of the prefab.. but the Instantiated version of that prefab
    }
}``` bare basic example
tawny edge
rich adder
#

thats the best way to put into practice and drill in the info

tawny edge
rich adder
#

like trying to replicate from scratch what you did without following the page

tawny edge
rich adder
#

oh yeah then keep at it 💪

tawny edge
#

after each section, the course instructs to work on your own personal thing based on the design document you made..
It's where i struggle the most

rich adder
#

yea cause thats where ideally you're not just copying info down, you're trying to force your brain to recount and rebuild that from memory / knowledge learned

#

I have horrid short term memory, its not so much a quick memorizing thing, maybe more of a "muscle" memory I think.

tawny edge
cosmic dagger
#

Very true; after watching a tutorial or learning smth from a blog, it's best to immediately redo the very thing you learned without looking at the resources

You will see how much you've retained and what you need to work on . . .

quartz oyster
#

I have this, works fine but for some reason on mobile its not smooth at all, I tried upping the animationDuration but it still wasnt smooth, i call it like this : StartCoroutine(MovePanel(rectTransform, rectTransform.anchoredPosition, openPosition));
on a button click

private IEnumerator MovePanel(RectTransform panelRect, Vector3 startPos, Vector3 endPos)
{
float timeElapsed = 0f;

while (timeElapsed < animationDuration)
{
    panelRect.anchoredPosition = Vector3.Lerp(startPos, endPos, timeElapsed / animationDuration);
    timeElapsed += Time.deltaTime;
    yield return null;
}

panelRect.anchoredPosition = endPos;

}

rich adder
#

code itself looks fine

quartz oyster
rich adder
#

from the manual

  • Android and iOS: Content is rendered at fixed 30 fps to conserve battery power, independent of the native refresh rate of the display.
lunar hollow
#

How can i change the Texture of a Specific Face and get the Texture of a Specific Face of a MeshRenderer?

rich adder
#

easier said than done. Iirc you need proper UV split and all that

lunar hollow
#

Oh wow

rich adder
lunar hollow
#

Im trying to make a Source based Lightning System (In source only the faces texture go either darker or brighter)

rich adder
#

You want to make your own lighting system ?

lunar hollow
#

Oh okay

swift crag
#

I don't understand what that means

tiny hearth
#

Not sure where to put this, but I've been getting this error everytime I try to compile:
UnityEditor.dll assembly is referenced by user code, but this is not allowed. UnityEditor.BuildPlayerWindow:BuildPlayerAndRun ()

It is only when I include a library folder of plugins:

#

None of these plugins (to my knowledge) have any unity editor reference.

#

ClientCommon, AsyncData, GameServerCommon, are all my libraries with no unity references anywhere.

#

Is there anyway I can cause unity to give a stack trace on the build error, or more information than just "but this is not allowed"?

verbal dome
eternal falconBOT
#
📝 Logs

Documentation

Editor logs

Windows: %LOCALAPPDATA%\Unity\Editor\Editor.log
MacOS: ~/Library/Logs/Unity/Editor.log
Linux: ~/.config/unity3d/Editor.log

Unity Hub

Windows: %UserProfile%\AppData\Roaming\UnityHub\logs
Mac: ~/Library/Application support/UnityHub/logs
Linux: ~/.config/UnityHub/logs

verbal dome
#

Editor logs

tiny hearth
#

@verbal dome```Fatal error in Unity CIL Linker

Mono.Linker.LinkerFatalErrorException: ILLink: error IL1010: Assembly 'Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be loaded due to failure in processing 'ClientCommon, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' reference

---> Mono.Cecil.AssemblyResolutionException: Failed to resolve assembly: 'Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'

at Unity.Linker.UnityAssemblyResolver.Resolve(AssemblyNameReference name, ReaderParameters parameters)

at Unity.IL2CPP.Common.AssemblyDependenciesComponent.CollectAssemblyDependencies(AssemblyDefinition assembly, Boolean throwOnUnresolved)

at Unity.IL2CPP.Common.AssemblyDependenciesComponent.GetReferencedAssembliesFor(AssemblyDefinition assembly)

at Unity.Linker.UnityLinkContext.ResolveReferences(AssemblyDefinition assembly)

at Mono.Linker.Steps.LoadReferencesStep.ProcessReferences(AssemblyDefinition assembly)

at Mono.Linker.Steps.LoadReferencesStep.ProcessReferences(AssemblyDefinition assembly)

--- End of inner exception stack trace ---

at Mono.Linker.Steps.LoadReferencesStep.ProcessReferences(AssemblyDefinition assembly)

at Mono.Linker.Steps.BaseStep.Process(LinkContext context)

at Unity.Linker.UnityPipeline.ProcessStep(LinkContext context, IStep step)

at Mono.Linker.Pipeline.Process(LinkContext context)

at Unity.Linker.UnityDriver.UnityRun(UnityLinkContext context, UnityPipeline p, LinkRequest linkerOptions, TinyProfiler2 tinyProfiler, ILogger customLogger)

at Unity.Linker.UnityDriver.RunDriverWithoutErrorHandling(TinyProfiler2 tinyProfiler, ILogger customLogger)

at Unity.Linker.UnityDriver.RunDriverWithoutErrorHandling()

at Unity.Linker.UnityDriver.RunDriver()
*** Tundra build failed (0.33 seconds), 1 items updated, 49 evaluated
UnityEditor.dll assembly is referenced by user code, but this is not allowed.```

#

Thank you. didn't know of the logs. I've discovered the problem.

verbal dome
#

What was it?

tiny hearth
#

I have client and server code in the same unity project; the client code has the "ClientCommon", and so does the server. These are seperate library folders. I seem to have forgotten to provide the necessary dependencies to the Client lib folder to handle it's library.

#

The struggle was not having a stack trace.

#

Thank you so much.

verbal dome
#

Np👍 Logs often have the info that is missing from errors

#

Was it related to newtonsoft here?

tiny hearth
#

Yes, it requires that dependency.

acoustic sequoia
#

Hey everyone, quick question. I have a Task running during an event in my game. when the user presses pause, the games timescale is set to 0. everything is the game pauses except on a very very rare occasion this method seems to run infinitly fast..

the method im about to share is supposed to spawn enemies every (x) amount of time.. but when i pause, the enemies will eradically spawn (RARE).

public async Task StartSpawning(RallyPoint activeRally)
  {
    if (activeRally.spawnsPerMin == 0)
    {
      Debug.LogError($"spawnsPerMin is set to 0 : {activeRally}");
      return;
    }
    currentRally = activeRally;
    isRallyActive = true;
    float elapsedTime = 0f;
    float spawnInterval = 0f;
    float rallyDuration = activeRally.totalRallyDuration;
    float spawnrRateMultiplierActivated = 1f;
    float rate = 60f / activeRally.spawnsPerMin;
    float critialMomentSpawnIntesity = 1 - (currentRally.critialMomentSpawnIntesity / 2f);
    float criticalPoint = rallyDuration * currentRally.critialMomentStartTime;

    while (isRallyActive)
    {
      elapsedTime += Time.deltaTime;
      elapsedTime = Mathf.Clamp(elapsedTime, 0f, rallyDuration);
      if (rallyDuration - elapsedTime <= criticalPoint) spawnrRateMultiplierActivated = critialMomentSpawnIntesity;

      rallyManager.rallyTimer.SetTimer(rallyDuration - elapsedTime);

      currentRally.TimerTextInitialize();
      if (elapsedTime >= rallyDuration)
      {
        currentRally.Completed();
        EndRally();
        return;
      }
      if (!isRallyActive)
      {
        return;
      }

      if (spawnInterval == 0f)
      {
        SpawnEnemyGroup();
      }

      spawnInterval += Time.deltaTime;
      spawnInterval = Mathf.Clamp(spawnInterval, 0f, rate * spawnrRateMultiplierActivated);

      if (spawnInterval >= rate * spawnrRateMultiplierActivated) spawnInterval = 0f;

      await Task.Yield();
    }
  }```
obsidian plaza
cosmic dagger
acoustic sequoia
acoustic sequoia
cosmic dagger
#

oh, so you don't want this to continue running?

obsidian plaza
#

it’s incorrectly pausing i think

swift crag
acoustic sequoia
swift crag
#

are you sure that SpawnEnemyGroup isn't malfunctioning?

acoustic sequoia
swift crag
#

you can throw some log statements in there to find out how many times your code is running

acoustic sequoia
obsidian plaza
swift crag
acoustic sequoia
swift crag
#

it could be anything

#

it could be a method that says if (Time.deltaTime == 0) { SpawnThreeTrillionSpiders(); }

acoustic sequoia
# swift crag well, I can't see the code
  {
    int enemyIndex = GetRandomEnemyIndex();

    Vector3 pos = Vector3.zero;
    float randomAngle = Random.Range(0, 360);
    for (int i = 0; i < currentRally.amountPerSpawn; i++)
    {

      if (inactivePools[enemyIndex].Count == 0 || activePool.Count >= activeEnemyLimit) continue;
      Enemy enemy = inactivePools[enemyIndex][0];
      enemy.player = player;
      enemy.data = enemyTypesArray[enemyIndex];

      inactivePools[enemyIndex].Remove(enemy);

      if (activePool.Contains(enemy)) activePool.Remove(enemy);
      activePool.Add(enemy);

      enemy.transform.position = player.transform.position + Vector3.up;
      enemy.transform.RotateAround(player.transform.position, Vector3.forward, randomAngle);

      enemy.transform.Rotate(new Vector3(0f, 0f, -randomAngle));
      if (pos == Vector3.zero)
      {
        Vector3 direction = (enemy.transform.position - player.transform.position).normalized;
        pos = player.transform.position + direction * currentRally.spawnDistance;

      }

      Vector3 newPos = pos + Random.onUnitSphere;
      newPos.z = 0f;
      enemy.transform.position = newPos;
      particleManager.CreateSpawnEffect(newPos);
      if (i == 0)
      {
        soundManager.PlayClip(enemySpawn, newPos, 1);
      }



      enemy.gameObject.SetActive(true);
    }

    int GetRandomEnemyIndex()
    {
      int enemyIndex = Mathf.FloorToInt(Random.Range(0f, enemyTypesArray.Length));

      if (inactivePools[enemyIndex].Count != 0 || enemyTypesArray.Length == 1) return enemyIndex;
      else
      {
        for (int i = 0; i < 10; i++)
        {
          int newIndex = Mathf.FloorToInt(Random.Range(0f, enemyTypesArray.Length));

          if (inactivePools[newIndex].Count != 0)
          {
            enemyIndex = newIndex;
            return enemyIndex;
          }
        }
      }
      return enemyIndex;
    }
  }```
swift crag
#

I would add a bunch of logging so that when the issue does happen again, you'll have more information

swift crag
acoustic sequoia
swift crag
#

Do you get a very large number of spawns in one frame?

verbal dome
swift crag
#

if you think it's pause-related, I'd suggest writing code to pause and unpause the game very rapidly. that might help to trigger the bug more often

acoustic sequoia
swift crag
#

is there a reason you aren't just using a coroutine?

#

I'm much more familiar with that behavior

obsidian plaza
#

i was about to say

acoustic sequoia
verbal dome
#

Most people use coroutines in this type of situations, yeah.

#

Only reason I really use async is for stuff that needs to run in the editor too (I know EditorCoroutines exists but what if I want them to also work in playmode)

acoustic sequoia
cosmic dagger
#

i don't think Task is affected by the timeScale, or unity related Time. maybe that's why it acts up randomly and runs . . .

obsidian plaza
#

i mean at the end of the day why not just hard code in that the code doesnt execute at 0 timescale

acoustic sequoia
swift crag
cosmic dagger
#

yeah, i've never messed with Task before, so this is uncharted territory . . .

swift crag
#

that's why this is weird to me, yes

#

you may be interested in this

cosmic dagger
#

Awaitable is their own version of using Task, right?

swift crag
#

It's an alternative, yes

acoustic sequoia
#

so here is what i'm thinking... I think when the game pauses specifically when the spawnenemygroup is suppoed to run, the while loop continues with the same elapsedtime -> resulting in running the same condition over and over again

verbal dome
swift crag
#

I've used it for a game before. The game actions are implemented as Awaitable-returning methods. If I'm just simulating game logic, I skip all of the visual effects and the methods basically run synchronously. If I'm displaying an action, I run effects and await the completion of each step

verbal dome
#

Which is usually the next frame

swift crag
#

All you're doing is throwing your task back into a queue

acoustic sequoia
#

ya, so should i have a check before spawning to check if the game is paused? (seems like a temporary fix)

cosmic dagger
acoustic sequoia
#

i guess i'll just do that just to see if i ever see the issue again...

swift crag
#

I'd suggest adding a check that you aren't spawning twice in the same frame

#

log a warning if it happens

#

that'll help you spot the issue if it manages to happen again

acoustic sequoia
swift crag
#

Using Task.Yield() lke that is very alien to me

swift crag
#

of course, if it's instantly resuming the task, then you'll spin forever (:

#

I don't know how it behaves

cosmic dagger
swift crag
#

I would suggest using Awaitable, which lets you explicitly wait for the next frame

acoustic sequoia
cosmic dagger
#

that'll stop it from running if the SpawnEnemyGroup methosd is called and uses deltaTime when it still has a value . . .

acoustic sequoia
# swift crag so what?

so, that means how every many frames i'm paused i will expect the enemy spawner to spawn that many times...

verbal dome
swift crag
#

oh, I see how the bug is happening

#

yeah, I get it

#
      if (spawnInterval == 0f)
      {
        SpawnEnemyGroup();
      }

      spawnInterval += Time.deltaTime;
      spawnInterval = Mathf.Clamp(spawnInterval, 0f, rate * spawnrRateMultiplierActivated);

      if (spawnInterval >= rate * spawnrRateMultiplierActivated) spawnInterval = 0f;
#

You spawn a group if spawnInterval is zero

#

You set it to zero if the value gets too large

#

If you pause RIGHT as it gets past this limit, it'll have a spawnInterval of zero every frame

acoustic sequoia
#

exactly

swift crag
#

This is just a bug in your code. It's written wrongly.

#

You should do something more like this

acoustic sequoia
#

so a quick fix is to have a check right there to see if the game is paused

swift crag
#
delay -= Time.deltaTime;

while (delay <= 0) {
  delay += interval;
  DoThing();
}

interval is how long to go between spawns

#

delay is how long until the next spawn happens

#

using while makes sure it works right even if the interval is so fast that you get more than one spawn per frame

#

(and, obviously, you'll want to spawn enemies in that loop, too)

#

There is nothing conceptually wrong with a zero-duration frame. Any time-dependent processes shouldn't proceed at all during it

swift crag
acoustic sequoia
#

im aware of this, this code of mine is old. i will subract it

swift crag
#

so, just rewrite it so that it spawns enemies in response to you going past the limit

#

instead of setting the counter to 0 and then reacting one frame later

acoustic sequoia
swift crag
#

you are running the game at 10 frames per second

#

delay -= 0.1 -> suppose delay is now -0.007

#

interval is 0.001. we add interval to delay until it becomes a positive number again

#

spawning eight enemies in the process

#

(i added an extra line to the example to call a method)

acoustic sequoia
swift crag
#

It is not strictly necessary, but it's more correct.

#

It's more relevant for things like fast-firing weapons

acoustic sequoia
swift crag
#

notice how deltaTime isn't used anywhere inside the loop

#

we are simply adding interval to delay until the delay value becomes positive

#

Your code does something entirely different. It checks if spawnInterval is too big and sets it to zero if that happens

#

which means that it can get parked at zero forever if you pause at the exactly correct frame

#

Your spawn condition has nothing to do with checking if too much time has passed. It only checks if spawnInterval is zero.

#

It does become zero if you just passed the threshold...but it also becomes zero if the game is paused at the wrong moment

acoustic sequoia
#

ok so i think i get it now.. correct me if i'm still wrong lol

  1. the game reaches the spawnenemygroup().
  2. then enters a new while loop for the delay.
  3. the interval is fixed and is used to reach the delay amount.
  4. once delay is reached, execute SpawnEnemyGroup()

correct?

swift crag
obsidian plaza
#

so basically my original solution wouldve worked

#

pause at the end of the frame

swift crag
#

No, that wouldn't have done anything

obsidian plaza
#

oh smh

acoustic sequoia
#

how do i pause at the end of fram?

swift crag
#

well, with Awaitable, you can ask to resume at the end of the frame

#

but that's non-relevant here

acoustic sequoia
#

ok

swift crag
acoustic sequoia
#

yeah

#

can't i just use a bool isPaused to prevent all of this?

swift crag
#

That's it

swift crag
#

There's a fundamental correctness problem with the existing code

acoustic sequoia
swift crag
#

Time.deltaTime is zero.

#

delay is currently 0.01

acoustic sequoia
#

yes

swift crag
#

Does anything happen?

acoustic sequoia
#

no becasue deltatime is 0

swift crag
#

Right. delay -= Time.deltaTime does nothing

#

and delay <= 0 is false, so the loop doesn't run

#

Now suppose delay is -0.01

#

What happens?

acoustic sequoia
#

i don;t want the condition to fail. that would complete the while loop

#

teh task would end

swift crag
#

The entire thing can sit in a while (true)

#

That is irrelevant

swift crag
acoustic sequoia
swift crag
#
while (delay <= 0) {
  delay += interval;
  SpawnThing();
}
#

This condition is now true.

#

We add interval to delay and call SpawnThing();

#

If interval is large enough, the loop terminates.

#

Otherwise, the loop runs again.

acoustic sequoia
#

i don't want to spawn thing lol

swift crag
#

It is a placeholder.

#

You can do whatever you want in there.

acoustic sequoia
#

i don;t want to do anything ! lol

swift crag
#

What?

acoustic sequoia
#

thats the whole point

swift crag
#

I don't think you're understanding anything I'm saying

acoustic sequoia
#

i must not be lol

swift crag
acoustic sequoia
#

when the game is paused. i want to do nothing and wait until unpaused

swift crag
#

your code subtracts from it one frame before it checks the value

acoustic sequoia
swift crag
#

Replace interval with how frequently enemies should spawn per second

acoustic sequoia
#

hold on a sec. i'm going to give you a block. and edit it so it's correct..

swift crag
verbal dome
#

delay is like the bird in flappy bird, falling lower and lower
When you fall too low, you tap it until you are high enough

swift crag
acoustic sequoia
#
    {
      elapsedTime += Time.deltaTime;
      elapsedTime = Mathf.Clamp(elapsedTime, 0f, rallyDuration);

      if (elapsedTime >= rallyDuration)
      {
        currentRally.Completed();
        EndRally();
        return;
      }

      if (spawnInterval == 0f) SpawnEnemyGroup();

      spawnInterval += Time.deltaTime;

      if (spawnInterval >= rate * spawnrRateMultiplierActivated) spawnInterval = 0f;

      await Task.Yield();
    }```
add what you are saying to this to make it work
#

i made the while(true) for you

swift crag
#
while (isRallyActive)
{
  elapsedTime += Time.deltaTime;
  elapsedTime = Mathf.Clamp(elapsedTime, 0f, rallyDuration);

  if (elapsedTime >= rallyDuration)
  {
    currentRally.Completed();
    EndRally();
    return;
  }

  float interval = rate * spawnrRateMultiplierActivated;
  delay -= Time.deltaTime;

  while (delay <= 0) {
    delay += interval;
    SpawnEnemyGroup();
  }

  await Task.Yield();
}

something along these lines.

#

note that I have renamed spawnInterval to delay (because that's what it represesnts now

#

the name was already misleading, though: it's not the spawning interval

#

spawnTimer could be more appropriate

swift crag
#

This kills the game

acoustic sequoia
swift crag
#

this is inside of the while loop.

acoustic sequoia
#

ok so when the game is unpaused.. the delay is always greater than 0.. correct?

swift crag
#

At the end of the frame, delay will always be greater than zero

#

No matter what

#

If it isn't greater than zero, the while loop will add to it until it's greater than zero

#

This is a nice invariant. We know that, on the next frame, delay <= 0 must be false (before we subtract Time.deltaTime, at least)

#

On a paused frame, Time.deltaTime is zero

#

So we are also guaranteed that delay <= 0 will still be false

#

and thus nothing can possibly spawn on a pause frame

acoustic sequoia
#

ok wait .. hold on, i'm not understanding how delay is just floating around with no regulation... can delay get way too big?

swift crag
#

Why would it? We only add to it until it's greater than zero

#

then we stop

#

We are very carefully regulating the value of delay, to the contrary..

obsidian plaza
#

r yall still on this..

acoustic sequoia
#

omg my mind is just not comprehending this... shit

obsidian plaza
#

lol its just funny cause i thought it was a 2 line change

acoustic sequoia
swift crag
#

See what happens.

acoustic sequoia
swift crag
#

That is why I suggested you work an example by hand.

#

Seeing how it behaves with:

  • intervals much longer than the frame time
  • intervals much shorter than the frame time

will illustrate why it's correct

cosmic charm
#

no longer can't move the object in the scene, why is that happening?

swift crag
cosmic charm
#

and no they are not static

acoustic sequoia
teal viper
cosmic charm
#

the witch

swift crag
#

I wonder if having a deactivated object selected is at all relevant

teal viper
#

Or is that just hovered on

swift crag
#

oh, that's just hovered

acoustic sequoia
teal viper
swift crag
cosmic charm
swift crag
#

Start at zero if it should instantly spawn

teal viper
cosmic charm
#

yes

teal viper
#

Then it moves.

acoustic sequoia
teal viper
cosmic charm
#

but it doest show this thing

swift crag
cosmic charm
#

what ever it called

swift crag
#

those are handles

cosmic charm
#

yes it doesn't show them

swift crag
#

oh, one thing

#

switch from "Center" to "Pivot" (the shortcut is Z)

#

I bet the handles are just way off the screen

#

sorry, awful crop

#

top left of the scene view

#

Center finds the center of all of the bounding boxes of the renderers and colliders on the object

#

which can be very far away from the actual pivot point

cosmic charm
#

oh shoot

#

yes

swift crag
#

Center mostly exists as a prank

#

It is useful at times...very specific times!

cosmic charm
#

thank you ....

#

omg you saved me

#

thank you so much

verbal dome
#

I've seen 3 instances of someone getting pranked by Center today

cosmic charm
#

I love you already

#

what ever this creature is, I'm a fan of it from now on

#

thank you so much

swift crag
prime goblet
#

it's very tricky because whenever you create a new project, your UI layouts and most general preferences get reset

#

same with pivot/center

#

quite annoying imo

verbal dome
#

Pretty sure you can save layouts as presets and stuff

weak talon
#

i have a room object with this script on it

[SerializeField] private Animator anim;
[SerializeField] private BoxCollider boxCol;

public bool doorLocked = false;

private void OnTriggerStay(Collider other)
{
    if (other.gameObject.CompareTag("Player") && doorLocked == false)
    {
        OpenDoorServerRpc();
    }
}
[ServerRpc(RequireOwnership = false)]
private void OpenDoorServerRpc()
{
    Debug.Log("ClientRPC received. Playing door animation...");
    if (anim != null)
    {
        anim.Play("Door Open");
    }
    else
    {
        Debug.LogError("Animator component is missing!");
    }
}

the boxCol component is the collider of the door which is a child object of the room
and i want to detect collision coming from the boxCol component and check if the collision touching the boxCol component is comparetag player and do something if it is
can someone please help how to do that

eternal falconBOT
heavy knoll
#

Anyone know how to correctly play sound for hitting and then destroying an object? Im currently using the same script for different objects and they are each having their specific data set in the inspector for them. I also have a SoundManager empty game object with 2 AudioSources. Just cant figure out how to get one sound and the other into the inspector slots.

teal viper
heavy knoll
teal viper
#

You can get the clip reference from the destroyed object for example.

#

destroySFX.Play(thisObjectSound)

#

Not play, but you get the point I hope

heavy knoll
#

what would thisObjectSound be?

#

so i'd get rid of the empty game object with the sources on it to play the sound?

teal viper
teal viper
#

soundManager.Play(sound)
And the sound manager would call the play one shot or something on the audio source.

heavy knoll
#

im confused though

#

how do i get the audio sources into the inspector?

#

cause when i try dragging them in it only puts the top audio source into the audio source reference i have

teal viper
#

Where are you dragging the audio sources from and to where(a prefab? An object in the scene?)

heavy knoll
#

but it only lets me use the top audio source from the SoundManager object in the reference when i drag it in

#

I want it to play the footstepsfx on getting damaged and dashsfx on getting destroyed

#

but i dont wanna just hardcode those sounds into the script because i wanna make another object eventually that will have a different sound when getting hit and destroyed so i can just change it in the inspector

teal viper
#

If you have a setup like this, it might be wiser to only reference the sound manager object in your destructible object and just call the appropriate methods on it. Referencing the audio sources directly beats the purpose of a sound manager.

heavy knoll
#

ooh ok, ya i just tried it like this cause i saw a post online with someone talking about good ways to do it and that was one of them

#

is there a better setup i should be using to play the different audio sounds for each object?

heavy knoll
teal viper
teal viper
heavy knoll
teal viper
#

Ideally, you'd use scriptable objects here so that the sound data is encapsulated in a separate object and doesn't clutter the destroyable object inspector.

heavy knoll
junior ivy
#

Let's say that I have empty GameObjectAbc and a MonoBehaviour ScriptAbc.cs for it.
Can I add GameObejcts and Componenets from that script to compose a tree where GameObjectAbc is a root?
If yes then how is this possible to add a GameObject as a child to the ScriptAbc component? I've read that components can't have GameObjects as parents.
In other words: I want to create a scene tree purely from the code

heavy knoll
#

i tried watching a few vids too talking about the basics of it, but none of what they were showing seemed to be close to what I'm trying to use scriptable objects for

#

It was all just like making a basic scriptableobject asset from the asset menu and then setting simple values in that but not actually using them for anything in the game

#

basically i dont rlly understand how to convert my current script with all the methods and variables within into a scriptable object system

eager spindle
#

but if you need to store the state of an item there's other ways to do it

#

seems to align with what you're doing

teal viper
heavy knoll
eager spindle
#

You only need one HarvestableResource, no need to derive it. Then set the dropped item to the item of your choice like rock or wood

heavy knoll
eager spindle
heavy knoll
#

uh idk, im still pretty new, that's just what i got recommended to use

teal viper
#

It depends on the context. At the moment I recommend to use scriptable objects for sound data, as apparently they want different sounds with different pitches and what not for different object types.

#

Then you could just pass the SO reference to your sound manager and it would play the desired sound with your settings.

eager spindle
#

Think of the workflow of prefab vs scriptable object

#

If you use a prefab, you can simply Instantiate destructible trees and rocks
For scriptable objects, you'll have to make a copy of the scriptable object, and represent that ScriptableObject in the world(through a tree/rock object)

#

I'm not saying avoid SOs entirely but think about why you need them

heavy knoll
# eager spindle You only need one `HarvestableResource`, no need to derive it. Then set the drop...

This is what i currently have right now, one script called ResourceNode on each object that i want to be its own thing like iron ore or gold ore and they have their own values set in the inspector for the script. And another script called Playerhit which is just like a temporary script i have to test the functions before i add my tool system. https://paste.ofcode.org/38wJnL6n2yU3rLnUvVFXHgh https://paste.ofcode.org/32h48wervqkLFVCtcswFgwF

teal viper
junior ivy
#

thanks, that's what I wanted to hear, now I'm sure

#

I'm learning with chatgpt and it tried to add GameObject as a child to the component and I freaked out

rich adder
eager spindle
#

chatgpt has never coded a game before in unity don't let it tell you what to do

#

everything it spits out is garbled hearsay

junior ivy
#

it's good, I was able to do advanced things in godot much faster in compare to manual research

eager spindle
#

it's even worse for godot

junior ivy
#

it was even worse in godot but I was able to recreate his intentions

rich adder
junior ivy
#

it's not perfect

eager spindle
#

because 3.x and 4.x API changed a lot, using Godot for 4.x can give very wrong answers

junior ivy
#

I would spam you out with questions if not AI

rich adder
#

we rather get questions to clairfy something than you going to GPT and learning worse

junior ivy
#

oh no, I'm not learning from it... I'm gathering info and learning from that

rich adder
#

not even about being perfect, is just bad. period.
you wont learn anything, and whatever you learn is probably flimsy at best

junior ivy
#

LMAO if I trusted this AI I wouldn't achieve anything