#๐Ÿ’ปโ”ƒcode-beginner

1 messages ยท Page 387 of 1

acoustic grove
#

no, they're all in the same file and using the same variable

astral falcon
acoustic grove
#

so it's object reference not set to instance of an object

#

but I can access it from start() anf fixedupdate()

astral falcon
acoustic grove
astral falcon
astral falcon
acoustic grove
#

no never

astral falcon
#

But you highlighted 231, is nto the error line?

rich adder
#

wait its not obj.HandlePhaseAdvance(); throwing null ?

acoustic grove
#

there is no error line in the code

#

yes, its obj.HandlephaseAdvance()

#

oh im sorry, yes, thats the error line. Player: 234 or something, obj.HandlePhaseAdvance() in UpdatePhase()

astral falcon
#

And if you debug.log(obj) its throwing null?

rich adder
#

oh okay because 231 in vs was showing was not it

acoustic grove
#

yeah, it doesnt exist when i try to print it to debug

astral falcon
acoustic grove
#

yeah sorry its not 231 i was a bit confused by the question but basically this works:
but this doesnt:

acoustic grove
astral falcon
#

Who is calling updatephase?

acoustic grove
#

GameManager

astral falcon
#

And do you get the error always?

acoustic grove
#

yes

astral falcon
#

so obj is never != null

acoustic grove
#

no, I never set it to null or anything

astral falcon
#

How do you instantiate your playeragent?

#

And show your line of gamemanager who is calling the updatephase

#

I assume you are calling the updatephase on the prefab you are instantiating, not the reference in the scene

acoustic grove
#

this part works

#

I'm not sure there is a reference in the scene if its just a scriopt?

astral falcon
#

this is how you call the updatephase everytime?

acoustic grove
#

yes every time

astral falcon
#

Can you show the full code of that gamemanager?

acoustic grove
astral falcon
acoustic grove
#

yes, Player is an object in th scene

astral falcon
#

and that player.getcomponent<player> is always working? or not

acoustic grove
#

yeah, it gets player fine

#

the debug in the gamemanager always prints

astral falcon
#

but the obj. thing still throws an error. weird setup there

acoustic grove
#

yeah

#

I think its something to do with the plugin

rich adder
#

try adding the scripts with the Green + to prefab

#

is it creating a prefab copy without those greens, remember green + means not applied to original prefab

astral falcon
rich adder
#

oh they mentioned ML agents thought maybe it creates copies?

astral falcon
#

Ahh yeh, that mgiht be a n issue if it handles those players by itself

rich adder
#

havent used ml agents in a very long time ๐Ÿ˜…

acoustic grove
#

thing is I have a demo that works fine using the same gameobject accessor

#

and has a mlagent

#

do you think I should try to maybe make a new project and try to copy over my codE?

robust kelp
#

!code

eternal falconBOT
exotic hazel
#

i need help. i got a script for car controler online. there is a component trail renderer. whenever i put on that componenet the speed of the car is stuck at a certain point. without the component its fine but with errors while playing. pls tell what i do

burnt vapor
eternal falconBOT
exotic hazel
burnt vapor
#

I'd assume after 8 minutes you would have send it

exotic hazel
#

the code's too long im sending in parts

burnt vapor
#

Not at all, just pointing it out

twilit sundial
#

hey this seems valid does it not?

exotic hazel
#

the error was at last line before i added the trail renderer but then the car's just stuck

hexed terrace
#

!code share code in a paste site when its so much

eternal falconBOT
exotic hazel
hexed terrace
#

now delete those massive chunks of code above

exotic hazel
#

ok

#

could someone help

ivory bobcat
twilit sundial
#

ah yea sorry

#

the index isnt out of range though i thought

ivory bobcat
#

It should be, for the error to be thrown.

#

You go to the line and check the possible values for index

#

Or determine if the array/collection could possibly be not the one you'd think it is.

hexed terrace
exotic hazel
hexed terrace
#

It's also doing GetComponentInChildren all the time, which is v.bad
And it has using UnityEditor.Callbacks; which means you can't have this class in a build

exotic hazel
ivory bobcat
#

We'd need to see the details/stacktrace of the error to know what's going on. Also your image above has no line count so we'll not be able to easily pinpoint your error. @twilit sundial

rustic timber
twilit sundial
#

yea i set it differently

hexed terrace
# exotic hazel i should remove unityeditor.callbacks?

Yes. But you may get errors removing it.. which will then also need fixing

and if the velocity is clamped when another component is attached, then the problem is probably in that class and you should share the code for that too

twilit sundial
#

to like 0 1

rustic timber
#

change to if (clickCount < string.count - 1)

ivory bobcat
#

I'm assuming the string collection is empty and that the first element doesn't exist thus index 0 threw a fit.

twilit sundial
#

so the string being empty matters

rustic timber
#

strings is an array of strings right? not a string

twilit sundial
#

yea

#

i meant string at the start

ivory bobcat
#

Reminder that the initialized array would be overwritten by the inspector values - think of the values in code as simply default values.

exotic hazel
twilit sundial
#

the empty ones

rustic timber
#

You're getting strings[strings.Count] which will try to get index N even though the max index is N-1. try what I posted

gaunt ice
#

index out of bound means you are trying to access some invalid index, elements in the array/list has nothing to do with that

exotic hazel
#
using System.Collections;
using TMPro;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;

public class CarGears : MonoBehaviour
{
 public TextMeshProUGUI Gear;
 public int GearNo = 1;
 public Rigidbody Car;
 float MaxSpeed;
 public CarController carController;
 public Speedometer speedometer;
 void Update()
 {
    Debug.Log(Car.linearVelocity.magnitude);
    Gear.text = GearNo.ToString(); 
    if(Input.GetKeyDown(KeyCode.G))
    {
        GearNo += 1;
        if(GearNo >3)
        {
                GearNo = 1;
        }
    }
    if(GearNo == 1)
    {
        MaxSpeed = 10;
        if(Car.linearVelocity.magnitude >= MaxSpeed)
        {
            carController.maxAcceleration = 0f;
            speedometer.maxSpeedArrowAngle = -20.47f;

        }
        if(Car.linearVelocity.magnitude < MaxSpeed)
        {
            carController.maxAcceleration  = 15f;
        }
    }
        if(GearNo == 2)
    {
        MaxSpeed = 22f;
        if(Car.linearVelocity.magnitude >= MaxSpeed)
        {
            
            carController.maxAcceleration = 0f;
            speedometer.maxSpeedArrowAngle = -80.277f;

        }
        if(Car.linearVelocity.magnitude < MaxSpeed)
        {
            carController.maxAcceleration  = 15f;
        }
             




 }
 if(GearNo == 3)
    {
        MaxSpeed = 30f;
        if(Car.linearVelocity.magnitude >= MaxSpeed)
        {
            
            carController.maxAcceleration = 0f;
            speedometer.maxSpeedArrowAngle = -133.352f;

        }
        if(Car.linearVelocity.magnitude < MaxSpeed)
        {
            carController.maxAcceleration  = 15f;
        }
    }
}
}
ivory bobcat
twilit sundial
#

im done out

#

this is the end of the line isnt it i learnt what tables and stuff were on luau

rustic timber
#

Yeah...

exotic hazel
#

whats the problem in that

languid spire
exotic hazel
#

no it isnt

languid spire
eternal falconBOT
exotic hazel
hexed terrace
#

should have used a paste site again.

exotic hazel
#

oh sry

#

!code

eternal falconBOT
languid spire
exotic hazel
languid spire
#

you could have formatted the code first ffs

exotic hazel
#

sry im a bit newer to unity

languid spire
#

go to the very last } on your code. Delete it then add it back. The code should reformat automatically. Then re post it

exotic hazel
#

nothing happened

#

!code

eternal falconBOT
exotic hazel
languid spire
#

that's better

gleaming kraken
#

cant believe that this is valid unity code

#
if (this is type)```
#

this is crazy to me

languid spire
#

and there is nothing 'crazy' about it.
if AnObject.Type could be AnotherType

burnt vapor
eternal falconBOT
burnt vapor
#

It's called pattern matching

#

In modern Unity you should be able to write this instead:

if (this is PlateKitchenObject @object)
{
  plateKitchenObject = @object;
}
#

There's a lot more to it, and it's actually very complex once you start implementing more types of pattern matching

rocky canyon
#

yup, seems valid

languid spire
#

C# should never have allowed the @ option to reuse keywords

rocky canyon
#

i used it yesterday.. but for some other reason

#
        string wavePattern = @"
                .                
              .   .              
            .       .            
          .           .          
        .               .        
      .                   .      
    .                       .    
  .                           .  
.                               .";```
#

something something literal verbatim string something something

broken cargo
#

But what could be a valid use case for pattern matching this? Surely you should know what type it is since you are in the same class.

burnt vapor
rocky canyon
#

ive never used this and not known what type this was

#

usually to assign values Like an initializer

burnt vapor
#

So for example, AbstractFoo is implemented by Bar. In a method AbstractFoo can check if this is Bar and emit speciasl behavior

#

I'll admit the use case is weird, but it is possible and valid

#
internal sealed class Bar : AbstractFoo
{
    internal void Bar()
    {

    }
}

internal abstract class AbstractFoo
{
    private void Foo()
    {
        if (this is Bar bar)
        {
            bar.Bar();
        }
    }
}

This is valid

broken cargo
#

yeah, I see that. But using derived class in your abstract class is 100% a mistake

languid spire
burnt vapor
#

Yep, for example that's a pretty good use case

rocky canyon
#
    public void InitializeValue(MyClass that)
    {
        this.Value = that.Value;
    }```
#

i never have good use-cases.. for much of anything lol.. i accidently learn new syntax all the time

burnt vapor
#

A similar keyword you might want to know about is base ๐Ÿ˜Ž

rocky canyon
#

ohh.. i still use TryGets to see if my classes use interfaces ๐Ÿ˜…

burnt vapor
#

When base is specified anywhere, the call points to a class/method that the inherited class implements

rocky canyon
burnt vapor
#

So that's somewhat related to this, where instead you specify something from this class specifically

rocky canyon
#

this is actually the only way i know how to check if something uses an interface

#

i been meaning to look and see if theres alternative methods

hidden heath
burnt vapor
# rocky canyon

This is actually different, because this checks for a related component with the interface, and not if the calling class implements it

#

So another class can implement this interface and this method will return that class instead

rocky canyon
burnt vapor
#

Compared to pattern matching this which checks on the calling class

rocky canyon
#

yea ur completely right

hidden heath
rocky canyon
hidden heath
torn vapor
#

Hey does anyone know why my Visual Studio doesnt see the namespace?
I have installed the plugin and it works in editor

broken cargo
burnt vapor
torn vapor
#

What is that?

rocky canyon
hidden heath
burnt vapor
#

Granted, only Bar() had to be renamed as to not be ambiguous to its class

rocky canyon
# hidden heath Oh.

i was just goofing off.. i wanted to use Debug w/ my own custom functions.. and still have unity's debugs accessible

#

was a dumb work-around.. but it was fun

broken cargo
burnt vapor
#

A way around this would be to also make an abstract implementation of Bar called AbstractBar and pattern match with that instead. AbstractBar would exist in the same assembly in this case and contain required abstract methods that Bar implements

hidden heath
burnt vapor
#

Then Bar implements AbstractBar, and AbstractBar inherits from AbstractFoo

#

Nice and complex ๐Ÿ˜„

hidden heath
#

Normally I use System.Random for procedural generation.

broken cargo
#

Yes, I think as a rule of thumb you should not pattern match "down", and there is no reason to pattern match "up"

broken cargo
burnt vapor
rocky canyon
#

the Crash() method just kicks you out of play mode.. b/c i have some scenes that only work when loaded additively thru the main menu

torn vapor
rocky canyon
#

if i try to play test em they are gonna be full of Null Reference Errors anyway

#

soo best to kick u out and say, nah bro.. not that way lol

fringe plover
#

!code

eternal falconBOT
fringe plover
#

https://hatebin.com/ckfdhcngte
Can someone help?
I made simple script to let player place any items on plate exept plate itself (it worked before i added plate check on line 25)
But now it doesnt let me place item because it thinks that im trying ot place same item on it...

rocky canyon
fringe plover
#

Wait

#

im dum

rocky canyon
#

!PlayerControler.instance.currentItemSO is wrong

#

lol

fringe plover
#

lemme try

rocky canyon
#

its just asking if the currentItem is not null in that example

fringe plover
#

Yeah it works

#

thank you

#

didnt saw that lol

rocky canyon
potent talon
#

hello i have a problem. I have a painting that i animate in 3DSMAX and when i start the game the painting start moving but i dont want to. How i can solve this. I made research and found this to maybe help me but nothing...

rocky canyon
#

need a boolean or some other transition between the two.. soo it doesn't transition until u set it true

#

animator.SetBool("BeginAnimation", true); for example

fringe plover
#

Id rather use trigger if u need to animate only once

cunning flint
#

why the links website so lagy

#

the website crash every sec

rocky canyon
#

either or.. main point having a parameter in the transition

rocky canyon
cunning flint
timid oriole
#

I want my door to open slowly when I use a co routine is that possible

swift crag
timid oriole
#

something like if hit.collider.CompareTag("Door") && Input.GetKeyDown(KeyCode.E) {WaitForSeconds(3) door.transform.position = new Vector3 (0, 90, 0)}

#

Assuming all this code is inside an Ienuerator

swift crag
#

well, this would set the door's position to [0, 90, 0] ...

timid oriole
#

yeah

#

like an open state of the door

languid wadi
#

is this script good for moving my player:

'''
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
// Speed of the character
public float speed = 1.0f;

void Update()
{
    // Get input from WASD keys
    float moveHorizontal = Input.GetAxis("Horizontal");
    float moveVertical = Input.GetAxis("Vertical");

    // Create a Vector3 for movement
    Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);

    // Move the character
    transform.Translate(movement * speed * Time.deltaTime, Space.World);
}

}
'''

swift crag
#

doors generally rotate

#

unless this is a sliding door

timid oriole
#

yeah u right

swift crag
#

also, it also wouldn't do anyting "slowly". it would wait 3 seconds and then instantly make the change

timid oriole
#

I meant rotate

timid oriole
#

Would I need a lerp then to move it slowly?

swift crag
#

It would be useful, yes, but using Mathf.Lerp or Vector3.Lerp or Quaternion.Lerp won't magically make it start rotating smoothly

#

you need to slowly change the rotation of the door over a period of time

timid oriole
#

Correct

#

I would have the start rotation then the end rotation then the duration it takes to get there I believe correct?

swift crag
#

write out the code you're thinking of.

frank zodiac
swift crag
#

because new users have enough on their plate

#

it is appropriate to learn after you get a bit of experience

frank zodiac
#

just takes a few lines of code

swift crag
#

there are multiple ways to use it and the complexity really is not necessary or helpful for a complete novice

burnt vapor
#

As a beginner it's miles easier to just get input directly rather than putting a new system behind it

#

Sure, it's better, but when you learn you should do it one at a time

swift crag
#

i'm a big fan of the new input system, but it is's not the first priority for a novice

frank zodiac
#

thats partially true i guess

languid wadi
swift crag
#

you didn't ask a question

#

beyond "is this script good?"

frank zodiac
#

whats your goal

frank zodiac
#

its a basic movement script

#

try it and see the results

languid wadi
#

it works but it lags. idk if its because of the editor or my pc or because of my script

swift crag
#

and what does "it lags" mean?

#

the game runs at a low framerate?

#

the character stutters?

zealous hatch
#

what would be the best way to have a prefab spawn in and grab a variable from a script on a game object?

i have tried:
Player = gameobject.find("Player") Player.GetComponenet("MyScript")
but does seem to work

burnt vapor
rocky canyon
zealous hatch
#

I have a bullet prefab that i am spawning in on click. I also have a variable on the player gameobject with a script that contains a variable that i need the bullet prefab to access

burnt vapor
#

Calling Find is not a good way to get something

burnt vapor
languid wadi
# swift crag the character stutters?

i dont know because i just have a scene with a plate as terrain and the player so i cant see if its just the player or the the game running at low framerate

rocky canyon
#

i have a singleton on my GameManager.. and it has a reference to the player.. making it easy to modify it or grab anything i need

zealous hatch
rocky canyon
#

not sure i'd singleton the actual player.. when u can just plop a reference somewhere

zealous hatch
#

which is a float

burnt vapor
#

Why not on the bullet, or the weapon shooting it?

#

Sounds like something the weapon would assign when you shoot the bullet

zealous hatch
languid wadi
burnt vapor
rocky canyon
#

yea, doesn't make sense for u player to have to know about the gun/bullet

#

it makes sense for the player to know its jump height.

burnt vapor
#

The weapon has the player as the owner, so that sounds like an easy way to get to the player for additional information

#

Benefit is that you can optionally assign additional stats from the weapon on top of this base speed

#

Only problem you should tackle is how you go from the weapon to the player

#

I'd argue a weapon is assigned an "owner" when the player picks it up

zealous hatch
#

if im instantiating a bullet, is there anyway i can pass the variable through that?

rocky canyon
#
  Bullet bulletInstance = Instantiate(bulletPrefab, bulletStartingPosition.position, bulletStartingPosition.rotation);
  bulletInstance.speed = bulletSpeed;```
this is how i do that stuff
burnt vapor
rocky canyon
#

if the bullet prefab has a Bullet.cs script u can just instantiate it as a Bullet

burnt vapor
#

Another way would be accessing public fields directly, but I'd argue having an Initialize method is better since it's clear what is required

#

Also, to be more secure, calling the method could flick a boolean to ensure it is actually initialized

languid wadi
#

Windows almost crashed

rocky canyon
#

both valid ways

rocky canyon
# zealous hatch if im instantiating a bullet, is there anyway i can pass the variable through th...
Bullet bulletInstance = Instantiate(bulletPrefab, bulletStartingPosition.position, bulletStartingPosition.rotation);
bulletInstance.Initializer(direction, speed, delay);
public class Bullet : MonoBehaviour
{
    public float speed;
    public Vector3 direction;
    public float delay;
    public bool IsInitialized { get; private set; } = false;

    public void Initializer(Vector3 dir, float spd, float del)
    {
        direction = dir;
        speed = spd;
        delay = del;
        IsInitialized = true;
    }

    private void Update()
    {
        if (!IsInitialized)
            return; // if not initialized return out of function
        
        // is initialized so do ur logic
        transform.Translate(direction.normalized * speed * Time.deltaTime);
    }
}``` or u can set them directly like Fused also mentioned..
`bulletInstance.speed = speed;` etc
queen adder
#

https://gdl.space/enacidoten.cpp

  • What will happen if i do (TurretTarget as ITarget).IsDead; // Gives a warning of 'cast is redutant' ? Answer: It will use derived class always
  • Do you suggest this structure and why?
burnt vapor
# rocky canyon ```cs Bullet bulletInstance = Instantiate(bulletPrefab, bulletStartingPosition.p...

This is what I would do:

public class Bullet : MonoBehaviour
{
    private float _speed;
    private Vector3 _direction;
    private float _delay;
    private string? _message;

    private bool _initialized;

    public void Initializer(Vector3 dir, float spd, float del)
    {
        this._direction = dir;
        this._speed = spd;
        this._delay = del;
        this._initialized = true;
    }

    private void Update()
    {
        this.ThrowIfUninitialized();

        // _message is not null
    }

    [MemberNotNull(nameof(this._message))]
    private void ThrowIfUninitialized()
    {
        if (!this._initialized || this._message == null)
        {
            throw new InvalidOperationException("Component is not initialized!");
        }
    }
}

When calling ThrowIfUninitialized, the code actually removes the nullabillity from _message because of the attribute.

#

But perhaps this is a bit complex for this topic

#

There's also MemberNotNullWhenAttribute for when the method returns a boolean. Useful for checking if you intiialized without throwing an exception

zealous hatch
rocky canyon
#

its a prefab.. (that has a bullet script)

#

w/o the bullet script it wouldnt make sense to do it that way

rocky canyon
#

this is solid tho ๐Ÿ‘

#

i need to write more code like that

burnt vapor
queen adder
rocky canyon
burnt vapor
#

There's also NotNullWhen for individual parameters that you pass that might be null. It uses the same system where it would not be null if the method returns true

#

Matter of fact, all internal Try methods that do these have that

rocky canyon
#

i always get reprimanded for useless this

burnt vapor
#

Code feels weird without it nowadays

rocky canyon
#

good, then im in good company

#

if im using any property / variable of the script im working in i unconsciously add this.

queen adder
rocky canyon
#

yes makes sense! ๐Ÿ‘

burnt vapor
#

I'm very used to thinking parameters are local when they don't prefix with this now, though it's also obvious depending on the color of the parameter in VS

#

Dunno, just an extra step in clarity that doesn't hurt ๐Ÿ™ƒ

rocky canyon
#

weird lol.. like "what is enabled?"

#

my local variables usually get an _

  • PublicVariable
  • privateVariable
  • CONSTANTVARIABLE
  • _localVariable
#

although, it is evolving more and more

#
public void Initializer(Vector3 dir, float spd, float del)
{
    direction = dir;
    speed = spd;
    delay = del;
    IsInitialized = true;
}``` still debating on how to do my functions parameters
#

usually i just do lowercase (simple and short variables) with </// Summary > XML to help clarify

#

but thats up for debate

swift crag
#

i prefer to just write this.foo = foo any time a parameter corresponds directly to a field

queen adder
swift crag
#

you can have billions of enum values

rocky canyon
#

i wish method signature parameters would instantly become that

swift crag
#

you're only limited to 64 distinct values if you're using "flag"-style enums

rocky canyon
#

this.foo = that.foo would be epic syntax

queen adder
swift crag
#

how are you using a string for TargetTag, then..?

#

some kind of weird comma-separated list?

rocky canyon
#

have you seen people that use Enums w/ string comparisons?

queen adder
#

I thought of letting the ITarget.TargetTag be anything and let the developer customize anything he wants. The default way i do implement is using TargetTag => this.tag on any MonoBehaviour. Since tags are changeable in runtime, i thought it would be better

swift crag
#

If you want to give an entity a set of tags, then you should just give each entity a HashSet<TargetTag>

#

what is a "target tag" here, anyway?

#

what does it respresent?

#

is it a kind of target ("grounded", "flying", "burrowed") ?

queen adder
#

TargetTag here is it's type. Like: Turret, BigTurret, LargeTurret

#

So i will use normal flags then

swift crag
#

why is the turret type stored on an ITarget?

#

does this represent the kinds of turrets that are allowed to shoot at the target?

queen adder
# swift crag why is the turret type stored on an `ITarget`?

Let me explain it in details: There is an AI Base class of all AI's. I thought if flag enums are limited, the normal enums are limited too but you prove i misunderstood the concept... So i thought of using a tag thing in ITarget to get the target type(target tag). AI Base class implements this as virtual and uses this.tag directly. But ITarget cant be an AI always. So i thought i shouldnt know the exact target type and use interface.

queen adder
swift crag
#

no, let's look closer at it

#

If you want to store every kind of turret separately, and you think you might have more than 64 turrets, then a flags enum would indeed be inappropriate

#

in that case i'd go with a HashSet<TurretType>, where TurretType is a non-flags enum

#

from a design standpoint, I think it'd make more sense for targets to have qualities that make them targetable, and for each turret to be able to shoot at enemies with the correct qualities

swift crag
#

in that case a flags enum would be fine

#

As for using an interface: that sounds fine

queen adder
#

No no you misunderstood. It just stores single type

#

man i am so bad at explaining

swift crag
#

that sounds wrong

rocky canyon
#

ROY G BIV Flag System ๐Ÿ˜…

queen adder
#

Okay i will try explain again. The ITarget is a gate way to a type and it's stats of an unknown type of a Target. This is because i shouldn't know the type at all. Firstly, i wanted to use **enum **which is correct and i will use now thanks to you so much Fen but at first stage, i thought it is limited... So whichever class implements the ITarget will need to tell it's type(tag).

The second stage of 'why i did this is': exactly deciding which one should shoot a type. So i created a serialized list of "acceptedTags" in AI Base class. But as you can see, if i wanted to rename something, it would be a headache. I used a list there because it is self-serialized by Unity and uh cool yeah

swift crag
#

Forget about the implementation details -- tell me how your game is going to work

#

specifically the part where your turrets shoot at stuff

rocky canyon
#

i wanna know 2

queen adder
#

There is a 2D platformer game and the turrets waiting some enemies to shoot. But their allies are in front of them too. The turrets shouldnt shoot the allies. Also there is way more enemies than a turret and some ally

#

Did i uh explained very well?

swift crag
#

Okay, so each thing that can be shot at needs to be able to tell you which team it's on

#

"friendly" or "enemy" at least

queen adder
#

Yeah friendly or enemy

#

Dont forget, there is not just one type of ally. I mean it could be 4, 7, 11, 25 i dont know it is unlimited type of targets

swift crag
#

That doesn't really matter. Every ally unit will say it's on the Ally team

#

The exact unit type doesn't matter here.

gleaming kraken
#

hey guys! So I tried to run the following code, and only the first one worked. At first I was confused since they were identical, but I realized that the else clause was indented ahead. In c# if statements, does indentation matter for else ifs and elses, similar in a way to a language like python?

queen adder
swift crag
slender bridge
swift crag
#
public Team GetTeam();

this would be in the interface

swift crag
swift crag
#

In the second screenshot, this block is inside of the if (player.HasKitchenObject()) block

#

In the first, it is after the block

slender bridge
#

you should go back to code monkeys tutorial

queen adder
swift crag
#

an enum for teams would be reasonable, yes

#

A turret can check if its team equals the target's team

#

and ignore the target if that's the case

#

It sounds like you wanted to use unit types to check if they're friendly or not

#

Is that the case?

queen adder
#

Great, thank you

#

Lastly, using Health and MaxHealth properties in interface kinda ugly to me but i need to access them somehow is it okay if you say?

swift crag
#

If every targetable thing has health and a max health value, then yes, that must be part of the interface

swift crag
# queen adder Yeah unit types

Explicitly putting the team in the interface will be better -- imagine a turret that can temporarily mind-control an enemy

#

you'd just have the enemy unit switch which team it says it's on

slow knot
#

I need help with UI's

#

I just coded everything over unity edito

#

and realized that it causes weird things in different screen sizes

burnt vapor
eternal falconBOT
slow knot
#

Mhm? what does it have to do with my code though

#

I mean UI cause problems usually

#

main camera size etc. changes...

burnt vapor
#

Is this not related to anything in your code? Then why did you ask it in this channel?

slow knot
#

For example, here, It never follows the mouse as it should, and it changes when screen size is changed too

float transparency = 0.5f;
Vector3 worldMousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
worldMousePosition.z = 0f;
Image imageComponent = rectanglePrefab.GetComponent<Image>();
Color color = imageComponent.color;
color.a = transparency;
imageComponent.color = color;
RectTransform rt = rectanglePrefab.GetComponent<RectTransform>();
rt.position = new Vector3(worldMousePosition.x - rt.rect.width * 0.1f, worldMousePosition.y, worldMousePosition.z);```
broken cargo
slow knot
broken cargo
slow knot
broken cargo
# slow knot Yep, I do have it

Try to print rt.position and mousePosition to the console and see how you can scale one to match what you expect. Also you might want to use rt.anchoredPosition

slow knot
broken cargo
slow knot
broken cargo
swift crag
#

you can't add that to a world-space position to get a meaningful result

#

Get rid of that and see how your code behaves.

stuck palm
#

with ontriggerenter, is there a way to check which collider on the object is being collided with? not the other collider, the collider of the original gameobject.

swift crag
#

You cannot.

stuck palm
#

shite

swift crag
#

If you have several colliders on one object, you need to split them up into multiple child objects

stuck palm
#

they are in children objects

swift crag
#

is your component attached to a parent object with a Rigidbody, then?

stuck palm
#

all the capsules are meant are children of the root parent. i want the "ontriggerenter" to only be triggered by the box.

swift crag
#

you can put different kinds of colliders on different layers

#

otherwise, you need to handle the trigger messages on the individual child objects

stuck palm
#

cant you also colliders triggers avoid layers?

#

terribly written, apologies

swift crag
#

you can tell the physics system to ignore collisions between two specific colliders, and you can also tell a specific collider to ignore specific layers

languid wadi
#

What is wrong here, i got 999+ errors

using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public float speed = 5.0f;
    public float jumpForce = 7.0f;
    public float mouseSensitivity = 100.0f;
    public Transform cameraTransform;

    private Rigidbody rb;
    private bool isGrounded;
    private float rotationX = 0f;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
        Cursor.lockState = CursorLockMode.Locked;
    }

    void Update()
    {
        // Mouse movement for looking around
        float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;

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

        cameraTransform.localRotation = Quaternion.Euler(rotationX, 0f, 0f);
        transform.Rotate(Vector3.up * mouseX);

        // Get input from WASD keys
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");

        // Create a Vector3 for movement
        Vector3 movement = transform.right * moveHorizontal + transform.forward * moveVertical;

        // Move the character
        transform.Translate(movement * speed * Time.deltaTime, Space.World);

        // Jump when the space bar is pressed and the player is grounded
        if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
        {
            rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
            isGrounded = false;
        }
    }

    // Check if the player is grounded
    private void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.CompareTag("Ground"))
        {
            isGrounded = true;
        }
    }
}

swift crag
#

did you look at any of the errors at all

swift crag
#

you can't just stop at "i saw an error"

ivory bobcat
languid wadi
ruby python
#

Post them

languid wadi
#

UnassignedReferenceException: The variable cameraTransform of PlayerController has not been assigned.
You probably need to assign the cameraTransform variable of the PlayerController script in the inspector.
UnityEngine.Transform.set_localRotation (UnityEngine.Quaternion value) (at <779cc116a5954f1c9b92496e62345641>:0)
PlayerController.Update () (at Assets/PlayerMovement.cs:29)

languid wadi
ruby python
#

You haven't assigned the cameraTransform in the inspector.

ivory bobcat
#

You probably need to assign the camera transform variable of the player controller script in the inspector

languid wadi
#

yea but before it worked

ruby python
#

That error is telling you that cameraTransform is empty, and as there nothing in the code that assigns it, you haveta manually do it in the inspector.

ivory bobcat
swift crag
#

clearly something has changed and now it doesn't work

#

rather than arguing with the error, read it and fix the problem

languid wadi
#

IDK HOW

#

thats why im asking here

ivory bobcat
#

At least the error is nice enough to tell you what to do ๐Ÿ˜…

swift crag
ivory bobcat
#

Which part of what was suggested are you having issues with?

languid wadi
ivory bobcat
#

Do you know how to drag the camera into the field in the player controller script via inspector?

languid wadi
#

wait

languid wadi
ivory bobcat
#

Show your hierarchy

languid wadi
#

wait

bleak glacier
#

Where should I learn Unity for 2D game dev? All of the official unity tutorials are all 3D.

languid wadi
swift crag
#

win+shift+s

languid wadi
#

when i do that it wants to save my project

#

not working

languid wadi
#

oh wow my script didnt show me the camera transform before because my pc is loading forever

#

now i saw the camera transform

#

wait

ivory bobcat
swift crag
#

windows key, shift key, S key

languid wadi
polar acorn
#

because if your game saved when you did that you hit ctrl s

#

not win+shift+s

swift crag
#

well, given that no combination of those keys will make the editor save the open scene,

#

(unless you're using a macbook)

#

but I doubt that, given that you're complaining about windows

languid wadi
polar acorn
languid wadi
#

Restarted Windows now it's working

#

Btw if you noticed, my Windows PC is trash and just don't do stuff or do stuff it shouldn't do. So something like that can happen with my windows

polar acorn
languid wadi
#

What's that

#

oh wow

#

thanks

#

I JUST RESTARTED MY PC AND THEN IT WORKED. MHHHHH Strange. why didnt it work before?? i pressed the same keys than before

languid wadi
cosmic dagger
#

It's a real thing, and it happens from time to time . . .

languid wadi
swift crag
karmic isle
#

wow coding is fun, something gratifying about seeing your work working the way ypu intended

im still in the tutorial so im sure itll become dreadful in the future when i actually start cracking

languid wadi
swift crag
languid wadi
swift crag
#

and yes, I've had issues where the screenshot tool decides to disappear until I restart

languid wadi
hidden heath
karmic isle
#

easy for me to get lost though

hidden heath
karmic isle
#

facts

slow knot
#

Everything is fine and enjoyable until i get stuck doing something

#

And then motivation and everything goes away pepePuff
Oh also, not to talk about people criticizing and never giving credits to what you made for hours and just complaining

timid oriole
#

If I want to perform an action over a certain peroid of time would I use coroutine in combination with input.getkeyup? Example filling up gas can from pump want it to take three seconds

hidden heath
broken cargo
cosmic dagger
slow knot
#

Struggling with UI now:/

timid oriole
#

A lot of the time when I have an issue peple are like just use unity learn

hidden heath
#

Then there is taking breaks because you can't figure something out. Then you come back to it later and figure out that what you couldn't figure out was as easy as one simple line of code.

slow knot
broken cargo
timid oriole
timid oriole
#

I think so

broken cargo
#

But both ways are valid anyway, whatever makes more sense

timid oriole
#

hmm I see

#

In your opinion in terms of handling pickups would you transform it to an empty holder or use setactive and just disable it when not held

#

What do you think is the optimal proper way

rocky canyon
#

i do the SetActive route

#

if im setting the transform to be the container anyway.. might as well just keep it there

timid oriole
#

Intresting but then don't you run into the problem where if you drop it just sets false and the item doesn't actually drop?

rocky canyon
#

i dont allow you to drop weapons.. if i did tho.. i would just instantiate a pickup prefab and drop it and just disable the actual object

broken cargo
#

or if your objects have a state, or a lot of logic switching parents might be easier

timid oriole
#

I see

#

for your drop though couldn't you just simply enable gravity and collider?

#

Then disable when you pick up

broken cargo
rocky canyon
#

^ this.. my pickups jsut tell my inventory what im picking up.

#

it doesn't have the actual logic tied to it

#

2 different objects entirely

timid oriole
#

So the action of picking it up merley enables the object to be active in your hiarchy which contains the logic

#

not the actual object you pickup tho

rocky canyon
#

ya, i destroy the pickup

broken cargo
ruby python
#

Af'noon kids. I was just wondering if anyone had a better approach to weapon unlocks based on XP/Level other than checking a stored XP/level value and doing a bunch of If statements? (ie, if level > x, unlockWeaponA etc.)

timid oriole
ivory bobcat
#

Set it once with chained conditional operators and evaluate later with enum flags

timid oriole
summer stump
timid oriole
#

the issue is althoguht I set it as a parent it doesn't mean its gonna be the position of the empty item equip

sharp pawn
#

Ok so i have problem Ive been working on my first game in unity for a bit now and i have a dev super weapon that im trying to put together and the weapon activates a raycast when you click and my problem here is after activating the debug command the makes a raycast visible its not coming from the weapon its even though Ive set it to do so itโ€™s actually making like a double raycast at 0, 0 is that because the weapon in question is a child of the main camera or is it something else?

ivory bobcat
ruby python
broken cargo
ruby python
sharp pawn
rocky canyon
#

" I need a double cheeseburger and fries "
" Okay sir, please pull around to the window "
" Alright, gotta go get my oil changed first, brb "

ruby python
#

weapon[] would be an array of weapon Scriptable Objects

rocky canyon
#
float[] xpThresholds = { 1000f, 2000f, 5000f, 10000f };```
```cs
for (int i = currentUnlockIndex; i < xpThresholds.Length; i++) {
        if (currentXP >= xpThresholds[i]) {
            unlockedWeapons[i] = true;
            currentUnlockIndex++;
        }else{ 
break;
}
}```
#

that was actually a pretty clever idea

ruby python
#

Idea is, basically a bullet hell type game, every level up the player gets to choose a random 'passive' power up from a list of three, but can also choose a primary (shooty shooty pew pew) and a secondary (AoE) weapon (so that weapons changes can only happen between level ups), so figuring out an unlock system for the primary and secondary weapons. ๐Ÿ™‚

latent magnet
rocky canyon
#

void CheckAndUnlockWeapons(float currentXP) { forloop that loops thru the thresholds and unlocks the weapons that correspond til the loop evaluates as false and breaks out }

ruby python
#

Yeah I like that. Seems very elegant to me ๐Ÿ™‚

rocky canyon
#

ya, lol.. i wouldn't have thought of it.. but when i heard aeth say it i instantly wanted to have a version so i can use too when it comes time

#

i dont have weapon unlocks like that.. but it could easily be used for achievement type things

#

after getting soo many xp, or coins

ruby python
#

I'm guessing, because I plan on using SO's for the weapons, I could remove this

unlockedWeapons[i] = true;

And instead do all of my 'display/selecting' logic there?

#

ie....

weaponName.text = unlockedWeapon[i].name;
weaponSprite = unlockedWeapon[i]
.sprite;

etc. etc. ?

rocky canyon
#

it'd be a bit different but yea basically weapons[weaponIndex].Unlock();

#
    public string weaponName;
    public Sprite weaponSprite;
    public bool isUnlocked;```
ruby python
rocky canyon
#

you'll just have to adapt it to ur games specifics

ruby python
#

Yeah, got a solid foundation to work from so that's awesome ๐Ÿ™‚

summer stump
ruby python
#

So, just thinking out loud now about the entire implementation ๐Ÿ™‚

'card' prefab that will be a button with all the info UI elements built in.
on Level up, game pauses, level up screen appears, button prefabs instantiate (from Object Pool) and populate using the above code using the weapons SO's.
Player clicks on a weapon, it gets registered in my GameManager (can change until the 'continue' button is pressed).
Continue button is pressed, weapon 'locks in' and is used by the player until the next time they level up.

queen adder
#

Sounds good to me so far

queen adder
#

Sorry just joining in

#

Can the player only have one weapon at a time? Or do they just unlock weapons as they level up?

ruby python
rocky canyon
# ruby python Not sure what you mean.

my friend made a game u spawn in... 1 wave of enemies come.. at the end of the level u collected X amount of coins.. u pick 1 of 3 weapons/powerups , it gets locked in.. and then u complete the entire next leve(wave) with that weapon.. then u pick a new one

#

or.. on his u could save up ur currency.. use the same weapon and then jump and upgrade or 2

ruby python
queen adder
#

Ahhh i see

#

Neat idea

ruby python
queen adder
#

Shouldnt be to hard to implement honestly

ruby python
#

So each time the player levels up, they choose a primary (shooty) weapon, a secondary (AoE) weapon and a passive ability (speed increase, rate of fire increase etc)

ruby python
queen adder
#

Thats good theyre pretty smart guys

ruby python
#

Yuh huh. lol.

rocky canyon
#

but it took me longer than i care to admit to do the scrollwheel selection.. and not have it jump entire indexes

queen adder
#

U using the old or new input system?

rocky canyon
#

both but on the mousewheel (old)

queen adder
#

I found it pretty ez with the new input system honestly

#

I use both to

rocky canyon
#

problem was my mouse wheel delta would change multiple increments at once

swift crag
#

my macbook trackpad produces a bunch of very small scroll events

#

this causes problems for anything that expects one scroll event to be a large amount of scrolling

#

[zooms ALL THE WAY IN to the shader graph in 0.1 seconds]

rocky canyon
#
   if(timer <= timeBetweenSelections)
                timer += Time.deltaTime;

            if(timer >= timeBetweenSelections)
            {
                if(Input.GetAxis("Mouse ScrollWheel") < 0f)
                {
                    ItemIdInt++;
                    timer = 0f;
                }

                if(Input.GetAxis("Mouse ScrollWheel") > 0f)
                {
                    ItemIdInt--;
                    timer = 0f;
                }
            }```
#

i had to use a janky timer

#

found a magic number of .2 worked snappy enough but didn't allow jumps

#

but who knows what the build will say

rocky canyon
ruby python
#

The only time I've tried a mouse wheel weapon change I used Brackey's weapon switching video/script, but then was told I was wrong cause it used transforms. lol.

latent magnet
#

i need help calling a function from main.js ```html
<script>type="module" src="main.js"</script>

swift crag
rich adder
#

no idea what you're trying to do here

#

or how it relates to unity

ruby python
swift crag
#

you'll have to point me to this exchange

latent magnet
ruby python
#

Oh it was months and months (maybe even a couple of years) ago.

latent magnet
#

i did, even went through it multiple times trying to figure out why it cannot find the method although it exists in main.js

swift crag
ruby python
summer stump
rich adder
latent magnet
#

alright give me a moment

late yew
#

I'm trying to expand the FOV of the camera when the player dashes to give more emphasis on the speed, dashDuration is set to 0.25f but even with it set to a higher int (such as 3) the camera is increasing the FOV and then not decreasing it. At one point I had it decreasing over time (I believe when the yiel was inside the while statement), but it would stop after the 0.25 seconds, meaning it wouldnt reach its original FOV. I'm not rly sure how to tackle this

IEnumerator CameraFOVBoost()
{
    float camFOV = mainCam.fieldOfView;
    mainCam.fieldOfView *= 1.3f;

    while (mainCam.fieldOfView < camFOV)
    {
        mainCam.fieldOfView = (float)Mathf.Lerp(mainCam.fieldOfView, camFOV, dashDuration * Time.deltaTime);
    }

    yield return null;
}
summer stump
latent magnet
summer stump
#

It certainly can get to the end value. The third parameter, when 1, will return the second parameter

Oh, got deleted

summer stump
ruby python
latent magnet
summer stump
#

Show the actual code

#

The most important part of the issue has not been shown yet

latent magnet
summer stump
#

I wonder if the issue is that that function is part of the variable hook

#

Not super well versed in js, nav may know more. I think he has mentioned using it a bit

swift crag
latent magnet
#

the issue seems to be resolved when i do <script>src="main.js"</script>
instead of the original setup <script>type="module" src="main.js"</script>
but it creates another problem for me in javascript itself
"cannot use import when script is not of module type"

latent magnet
latent magnet
rich adder
rich adder
latent magnet
#

nope, tested it

#

cannot import inside jslib file

rich adder
#

not in the jslib file

#

use the jslib file to further call JS in another file

#

hmm actually I have to go refresh my memory on how modules work lol

latent magnet
#

yea that works for the loaded variable

#

but what if i wanted to use an external library

#

i had to import main.js into the plain (not module) js file

#

and that did nothing but the same error as pervious

#

the jslib cannot read whats in a module js file

rich adder
#

yeah apparently this has been asked on the forums but no reply threads

worthy merlin
#

https://gdl.space/isiwuzavig.cs
I am working on a script that uses an Onvalidation to allow me to create variations of my in-game waves in the inspector. I've made alot of progress on it but last night encountered an issue where after stopping the game, the on-validation would run a wipe any enemyWavesWithVariation items I had in it. Depsite the value of wavesTillVariation not changing during runtime.

I decided to try opting for a new solution by editing those values outside of that field but now have the problem of line 104 not making list items when I Add an item to the list in the inspector.

Thinking on this idea I doubt it will actually solve the problem but I wanted to through out some possible solutions as I am unsure where to go. Any advise on the base problem would be amazing!

strange bay
raw token
latent magnet
swift crag
#

interop between multiple languages makes things more fun

#

you get a lot of extra...~mystery factor~

rich adder
raw token
#

I love JS a little too much. Never knowing just what it's doing with my code under the hood makes me feel alive

latent magnet
latent magnet
#

thats what im using atm

rich adder
#

I use interop because its the only way c# can interact with JS when doing ASP.net (web developement c#)

latent magnet
rich adder
#

oh yeah I think its the limitation of jslib and also wondering what you asked

#

someone mentioned that jslib are Emscripten JS library files.

#

no idea what that even is, as I barely know js lol

#

ohh is just this.. "Emscripten is an LLVM/Clang-based compiler that compiles C and C++ source code to WebAssembly"

late burrow
#

ok reverse list doesnt work

#

should i make array of arrays to determine x of largest numbers in array not larger than y

worthy merlin
swift crag
#

why do you need to use OnValidate here at all?

raw token
# latent magnet does it differ alot from vite?

Sort of different concepts... Before we had the more modern ESM module syntax of import/export, the CommonJS pattern was more prevalent, using require() and module.exports = instead. Even though modern browsers all pretty much natively support ESM modules nowadays, most web projects still have their bundlers transpile your ESM code down into CommonJS syntax (and a loader) for wider compatibility.

So if your Unity JS thingies will be interacting with code in your Vite project, I think ideally you'd probably be writing them within the Vite project's source as ESM modules and running them through the build process for dev/distribution (actually it sounds like this may be what you're already doing?). In any scenario, whether you should be using the type="module" attribute on the <script> element to load depends on whether or not the built script is in ESM or CommonJS format, and/or whether or not this HTML is being processed/generated by Vite.

But yeah... maybe better to try and get your simple example to work outside of Vite first - since there doesn't seem to be a lot of good material on the subject around on the net - to ignore the complexity added by the build process, for the moment.

swift crag
#

this looks like runtime logic

#

OnValidate isn't even going to run at all in the built game

latent magnet
#

and thank you to the other guy

#

i will perhaps give you my results, maybe in the future someone stumbles upon the same problem i had

worthy merlin
swift crag
#

I would set up wave templates in the inspector

#

and then use those to create "real" waves at runtime

worthy merlin
#

So... I need onValidation as its what runs outside of runtime. I use that to figure out when there is a change in variables, and if that change is with wavesTillVariation, then it knows to change the list

worthy merlin
swift crag
#

You're having problems because you're mucking with your serialized data.

#

Make the wave definitions read-only. When the game is running, use those wave definitions to create randomized waves

worthy merlin
#

I'm sorry but I am not sure what you mean. Is the solution you are talking about meant to build off of what I currently have? Or is it another solution alltogether.

swift crag
#

Explain what your game is actually going to do.

#

No implementation details at all: just gameplay

sullen zealot
#

hello! how can i change thhe ambient color in rendersettings in script? do i use the ambientSkyColor ?

sullen zealot
#

thanks

timber tide
#

oh there's also that ambientSkyColor like you said

#

try both

worthy merlin
# swift crag No implementation details at all: just gameplay

Ok.

When the game starts this wave System script is going to be running in the background. Based off of the current wave variation it would spawn x clusters of x amount of enemies randomly in their spawn area. When all enemies are destroyed, the wave will end and the code will add 1 to the currentwave count. As this number increases, the code is going to watch for when the player has made it passed wavesTillVariation amount of waves, everytime that happens it will change the current variation to the next one I made, this way every x amount of waves, it has up the difficulty with a new set of enemies. Whether those enemies are a new type, or a select amount.

https://gdl.space/lanufowaga.cs

swift crag
#

Okay, so at regular intervals, you compute a new "wave variation", and the "wave variation" tells you what to spawn in each wave

worthy merlin
#

yes

swift crag
#

I just don't understand why you need OnValidate -- or any editor-specific code -- to make this work. Why are you editing "wave variations" outside of play mode? Why do they even exist outside of play mode?

dim wharf
#

Does OnDisable work on non-monobehaviour objects? Because I have a non-monobehaviour object with listeners and I don't know when I should disconnect/unsubscribe

slender nymph
#

no, only monobehaviours receive unity messages like Update, OnDisable, Awake, etc

swift crag
#

(ScriptableObject can recieve those as well!)

#

i hope, at least

slender nymph
#

ah yeah, i should have been more specific since SOs receive some of those too (not Update though)

dim wharf
#

Hmm. Do I have any options on when I can unsubscribe listeners for basic objects?

swift crag
#

an OnDisable method on a plain old C# class means absolutely nothing to Unity

dim wharf
#

Like an ondestroy or smth

swift crag
#

explain what you are actually doing here

slender nymph
swift crag
#

you might need to listen to something like Application.quitting or SceneManager.activeSceneChanged. It depends on what your intent is here

dim wharf
#

I have a plain object with listeners and I dont know when to disconenct/unsubscribe them since I dont have an OnDisable

swift crag
dim wharf
#

isnt not unsubscribing bad?

swift crag
#

it depends entirely on--

#

yeah

#

It Depends

#

Explain what you're doing.

wintry quarry
swift crag
#

We can't answer your question without knowing what you're doing.

wintry quarry
#

Basically you should unsubscribe when you're done with the object

#

whenever that is

#

you can make it IDisposable

#

and make sure you Dispose it when you're done with it - and even in the Finalizer as a fallback

#

This is only necessary when the publisher of the event lives longer than the subscriber

#

if they both go away at the same time you don't need to unsubscribe.
Or if the publisher goes away first, you don't need to unsubscribe

#

One example of being "done with the object" would be... let's say your listener is a Weapon and it's listening for the player to fire off an "OnUse" event.

When you unequip the weapon is when you would unsubscribe in that case.

worthy merlin
# swift crag I just don't understand why you need OnValidate -- or **any** editor-specific co...

I am using that code to assign values to each variation of the waves. Since every level (scene) in my game will progress a little differently (such as a special type of enemy shows up at wave 15 in x level and not until 25 on y level), I need to be able to declare how many variations there will be and then assign values to each variation that would be unique to that level alone. Since I am not asking the player to assign these values in runtime, I am handling them on the inspector. The reason OnValidate is necessary is because that is the only way (that I am aware of) that I can see if the wavesTillVariation has changed, add all of the enemyWaveVariations to a list, and edit that list with values that will be unique to that list.

So if I am making a level, with 10 waves, and a variation in difficulty every 2 waves, there would be 5 variations of these waves that would require unique configuration by me so the game has a twist as the difficulty increases.

swift crag
worthy merlin
#

Yep

dim wharf
#

I basically just want to unsubscribe cause I think it might be bad. Executor handles invoking a string to change the description of a UI element I have

#

But they should be no longer in use at the same time so

#

I guess unsubscribing isnt so necessary in this case(?)

swift crag
#

see Praetor's messages again -- they explain when you must make sure you've unsubscribed

dim wharf
#

Yes, I am referring to those

#

and ^ is my conclusion

#

Thanks!

slender nymph
#

but how is OnDisable being called there

swift crag
#

so all of these Executors are responsible for inserting text into one big description area?

dim wharf
late burrow
#

i tried to make array of lists but instead it made list of arrays?

late burrow
#

new List<string>[0]

wintry quarry
#

However - is that a static event?

dim wharf
#

it is

wintry quarry
#

if it's a static event, the lifecycle of the event is definitely longer than this instance.

#

so yeah you should unsubscribe when you stop showing the UI or whatever

dim wharf
#

Ah I can definitely work something out

polar acorn
#

An array with size 0 by the way

#

so it can't actually hold anything

wintry quarry
misty pecan
#

Is there anything wrong with putting a collider and testing for collisions inside a script on a particle system object? It seems to not work.

late burrow
#

ah ok i confused code order

summer stump
#

May be more what you are looking for

misty pecan
summer stump
#

OnParticleCollision I guess

summer stump
wintry quarry
wintry oracle
#

hello guyes how can i make the player to climb any thing i need the script pls

wintry quarry
summer stump
#

The Three Commandments of OnCollisionEnter:

  1. Thou Shalt have a 3D Collider on each object
  2. Thou Shalt not tick isTrigger on either of them
  3. Thou Shalt have a non-kinematic 3D Rigidbody on at least one of them

credit: digiholic

wintry quarry
#

(non-kinematic Rigidbody)

misty pecan
summer stump
misty pecan
#

Im very confused

polar acorn
summer stump
wintry quarry
#

if you want to detect collisions with particles specifically, that's a very different beast than a normal physics collision detection

#

if you want just collisions between Rigidbody2Ds with Colliders, then the three commandments above apply (in 2d)

misty pecan
#

first i instantiate the object, in a bullet script.

if (collision.gameObject.TryGetComponent<Enemy>(out Enemy enemyScript))
{
Instantiate(bombExplosionPrefab, transform.position, transform.rotation);
Destroy(gameObject);
}

then, this is the code in the bombExplosionPrefab

private void OnCollisionEnter2D(Collision2D collision)
{
Debug.Log("Test - Collision is running");
}

wintry quarry
misty pecan
#

the bombExplosionPrefab and an enemy, it is instantiated and then whatever it is touching i want it to run code

wintry quarry
#

assuming it just explodes instantly and you want to know what it touched

wintry quarry
#

don't put a collider on the explosion prefab

misty pecan
#

Ok thank you i will try

formal venture
#

Question regarding Unity UI Toolkit. How do i cache a visual element like for example Label, so i dont have to query for it in every single new method i need?

rich adder
#

store it in a visual element

rich adder
#

ahh uquery.. I use c# ones

wintry quarry
#

Note also that the examples are annoyingly not using the generics to their full extent.

Button result = root.Q<Button>();``` You can do this instead of using VisualElement
ruby python
#

Not sure if I'm in the right place for this one, but would anyone have an idea on how to deal with collisions with a VFX Graph based flamethrower type weapon? Would a few raycasts with slight angle offsets be the best way?

rich adder
#

does it have collisions like particle system ?

ruby python
#

As far as I am aware, VFX graph doesn't interact with 'standard' collisions, it has it's own collision objects within the graph itself. ๐Ÿ˜•

rich adder
#

wow they dont have it.. thats balls..

#

I guess if you can get their positions you can do some overlaps or something
or time a Spherecast by "growing" the distance of cast

ruby python
#

Yeah, I think (and going from hazy memory) because VFX Graph is GPU based and Unity physics is CPU based, there's no 'simple' way for them to talk to each other.

rich adder
#

yeah you're right its all GPU based

#

I was just hoping unity made a node for it or something lol

ruby python
#

But I did just have a thought, I could just make a cone object with a mesh collider/trigger and turn it on and off when firing or not.

rich adder
#

grow the size and distance of spherecast with deltaTime

ruby python
rich adder
languid wadi
#

My cam is weird. This is my code of my cameracontroller:

using UnityEngine;

public class CameraController1 : MonoBehaviour
{
    public Transform playerTransform;
    public Vector3 offset = new Vector3(0, 1, -5);
    public float mouseSensitivity = 100.0f;
    public float distance = 5.0f;
    public float minY = -20f;
    public float maxY = 80f;
    public float smoothSpeed = 0.125f;
    public LayerMask collisionLayers;

    private float rotationY = 0f;
    private float rotationX = 0f;

    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    void LateUpdate()
    {
        // Get mouse input
        float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;

        // Update rotation values
        rotationY += mouseX;
        rotationX -= mouseY;
        rotationX = Mathf.Clamp(rotationX, minY, maxY);

        // Apply rotation to camera
        Quaternion rotation = Quaternion.Euler(rotationX, rotationY, 0);
        Vector3 desiredPosition = playerTransform.position - rotation * Vector3.forward * distance + offset;

        // Check for collisions
        RaycastHit hit;
        if (Physics.Linecast(playerTransform.position + offset, desiredPosition, out hit, collisionLayers))
        {
            desiredPosition = hit.point;
        }

        // Smoothly move the camera
        transform.position = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
        transform.LookAt(playerTransform.position + offset);

        // Rotate the player capsule to face the direction of camera rotation
        playerTransform.rotation = Quaternion.Euler(0, rotationY, 0);
    }
}

will send video how weird my cam is

rich adder
languid wadi
rich adder
#

none, just dont use it

ruby python
rich adder
#

I just find Colliders clunky

rich adder
languid wadi
# rich adder none, just dont use it

Better?

using UnityEngine;

public class CameraController1 : MonoBehaviour
{
    public Transform playerTransform;
    public Vector3 offset = new Vector3(0, 1, -5);
    public float mouseSensitivity = 100.0f;
    public float distance = 5.0f;
    public float minY = -20f;
    public float maxY = 80f;
    public float smoothSpeed = 0.125f;
    public LayerMask collisionLayers;

    private float rotationY = 0f;
    private float rotationX = 0f;

    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    void LateUpdate()
    {
        // Get mouse input
        float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity;

        // Update rotation values
        rotationY += mouseX;
        rotationX -= mouseY;
        rotationX = Mathf.Clamp(rotationX, minY, maxY);

        // Apply rotation to camera
        Quaternion rotation = Quaternion.Euler(rotationX, rotationY, 0);
        Vector3 desiredPosition = playerTransform.position - rotation * Vector3.forward * distance + offset;

        // Check for collisions
        RaycastHit hit;
        if (Physics.Linecast(playerTransform.position + offset, desiredPosition, out hit, collisionLayers))
        {
            desiredPosition = hit.point;
        }

        // Smoothly move the camera
        transform.position = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
        transform.LookAt(playerTransform.position + offset);

        // Rotate the player capsule to face the direction of camera rotation
        playerTransform.rotation = Quaternion.Euler(0, rotationY, 0);
    }
}
ruby python
# rich adder yeah whatever works

I'm working on performance more than anything with this prototype idea and figured it might be better to use the trigger rather than a bunch of raycasts.

rich adder
languid wadi
rich adder
languid wadi
languid wadi
ruby python
# rich adder raycasts are quite efficent

I'll do some tests using both methods and see which one is more performant. Getting obsessed with performance because I know later when the player is progressing through the game there is going to be a loooooooot going on, especially with the enemies and pathfinding.

rich adder
languid wadi
rich adder
#

dont "over-optimize" where you don't need to

ruby python
rich adder
ruby python
#

I'm even using For loops instead of foreach because apparently they're very slightly more efficient. lol.

ruby python
willow scroll
eternal needle
ruby python
#

I always have this issue when putting together a prototype that I've never really paid much attention to because I'm learning, where every few seconds there's a stutter, due to the whole garbage collection thing, so with this protype I'm doing everything I can to improve performance/minimise garbage collection etc. I'm still learning so I'm going to get things wrong. lol.

ruby python
austere gyro
#

How to make a timer that activates a function?(pls help)

rich adder
willow scroll
austere gyro
rich adder
#

"how to make a timer in unity"
"how to call a function in unity"

rich adder
#

in before:
"none of them work"
"I couldnt find anything"

willow scroll
# austere gyro yes

I think I was able to find quite a few. You might have checked them all already, do they contain wrong information?

ruby python
#

Like I said, I'm still learning, so fully accept I could be wrong. But if I ask a question and get an answer and nobody disagrees at the time I'll take it as read as most people in here know way more than I do. ๐Ÿ™‚

willow scroll
#

You can do whatever you find, but there is surely a reason for C# to introduce a foreach loop, if everything done with it can be achieved with a normal, for

eternal needle
languid wadi
#

can someone help me please i tried another camera script, this time i used one from github, but same bug.

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

public class cameramovment : MonoBehaviour
{
    public float mouseSensitivity = 50;

    public Transform playerBody;
    float xRotation = 0f;


    // Start is called before the first frame update
    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
    }

    // Update is called once per frame
    void Update()
    {
        float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;

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

        transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
        playerBody.Rotate(Vector3.up * mouseX);

    }
}

or is it my fault:

ruby python
languid wadi
#

what

rich adder
#

nvm

languid wadi
#

huh ok

rich adder
#

that was someone else. Also why did you put deltaTime back on the mouse ๐Ÿค”

languid wadi
#

i didnt

#

wait

swift crag
#

it's right there..

#

you need to pay at least a little attention to the code you're copy-pasting from the internet

rich adder
#

esp gpt

swift crag
#

If you are struggling to get started, you should drop this and use !learn

eternal falconBOT
#

:teacher: Unity Learn โ†—

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

languid wadi
rich adder
#

copied *

eternal needle
# ruby python Oh yeah it probably is, but, still learning, so when I get more experience with ...

One thing you should always do is a quick profile on if these things matter. Sometimes people who give the advice are wrong or express it in the wrong way. I even remember one guy, who definitely was decent at coding, was confident that his math solution was more efficient than a bunch of if statements checking the same things. (It was something with checking a bunch of angles). Even after being told otherwise, he took hours on his math solution only to abandon it because if statements were more understandable and it turned out it was more efficient.

languid wadi
eternal needle
#

One trap people fall into is "X is quicker than Y" when its 0.00001 ms faster if one case that doesnt actually happen in your game.

ruby python
# eternal needle One trap people fall into is "X is quicker than Y" when its 0.00001 ms faster if...

Oh yeah I get everything that's been said. I know it can be a subjective thing, but this is how I best learn things. I ask questions on here a lot of the time because I find it easier to understand something if someone explains it/tells me where to look in any code (if that makes sense) rather than looking at documentation which is really 'clinical' etc. (not sure if that makes sense to anyone. lol.)

But yeah, I do get it and I do very much appreciate the patience and help ๐Ÿ™‚

eternal needle
ruby python
languid wadi
strong wren
#

how do i fix this error? its not rlly affecting my game but i would like to fix this

summer stump
#

Then you can open those windows again

strong wren
#

ok

dusty shell
#

would it be smart to get move input for running state and for walking state instead of just using that of walking state?

rich adder
dusty shell
#

I get just the move input from the walk and it's working fine for the most part but the character has to be running before they can walk(running is meant to be the default state)

#

it's like valorant if y'all ever played, I'm tryna turn it 2d for the fun of it

rich adder
#

bool walking = Input.GetKey(KeyCode.LeftShift)
float currentSpeed = walking ? walkSpeed : sprintSpeed

dusty shell
#

i made a whole input action for it

rich adder
#

oh the new input system right its different, just an example though..you just need a bool from the walking action ๐Ÿคทโ€โ™‚๏ธ

dusty shell
#

yeahhh i get you thanks

vale bronze
#

does anyone know why Unity is throwing a "NullReferenceException" on the for loop?

    public InventorySlot[] inventorySlots;
    public GameObject inventoryItemPrefab;
    public void addItem(Item item)
    {
        for (int i = 0; i < inventorySlots.Length; i++)
        {
            InventorySlot slot = inventorySlots[i];
            InventoryItem inventoryItem = slot.GetComponentInChildren<InventoryItem>();
            if (inventoryItem==null)
            {
                spawnNewItem(item, slot);
                return;
            }
        }
    }

the attached image is InventorySlots

It could be a really stupid mistake I'm making but I have no idea what is causing it.

wintry quarry
vale bronze
#

the for loop

wintry quarry
#

which line

#

for (int i = 0; i < inventorySlots.Length; i++) < this one?

#

Show the full error message

vale bronze
#

That's the part that's confusing me

wintry quarry
#

And that's line 11?

vale bronze
#

yeah

wintry quarry
#

If that's line 11 then iventorySlots itself is null'

vale bronze
#

I cut some of the code out because it didn't feel necessary to send

vale bronze
wintry quarry
wintry quarry
#

You'll want to look at the full stack trace here

vale bronze
#

found the culprit haha

#

you were right about the AddComponent part. for some reason I was trying to add the component when I should have just been using GetComponent

vale bronze
#

thanks :)

dusty shell
#

Anyone know How I can make an online system or a good yt video that explains it?

raw token
remote osprey
#

hello

#

I have a question about architecture

#

I see a lot of people leaving the input handling only for a single class.
That seems wildly inneficient to me because then every observer would receive the input

#

What are the benefits of this approach?

swift crag
#

I see a lot of people leaving the input handling only for a single class.

I don't understand what this means

remote osprey
#

One class that receives the input and sends an event to other classes that care about that input type

swift crag
#

it's a bit of indirection, but i don't see how this leads to

then every observer would receive the input

summer stump
#

because then every observer would receive the input

And what does this mean?

swift crag
#

unless you only had one gigantic OnInput event

remote osprey
#

because for example, a card can be dragged

#

it needs to know if it's been clicked on

#

so the input manager receives the input click and sends a OnClickEvent to all objects that care about clicks

#

then the Card checks if it's the one that's been clicked

#

seems overly complicated to em

#

not sure i should be asking here at beginner

swift crag
#

You wouldn't have each card individually check if it's being clicked on, because that'd be a huge pile of wasted raycasts

#

You would have a class whose job is to handle clicking on and dragging cards around

swift crag
remote osprey
#

but why not have all that input checking be done on the Card class indirectly?

#

also, what is an input manager then?

swift crag
#

doesn't it sound less efficient to have all of your cards individually ask the input system if the mouse has been clicked?

swift crag
remote osprey
#

you said it had nothiing to do with an input manager

#

so what is an nput manager, then?

#

That's what I meant to say

#

I think you miight've misunderstood me

remote osprey
remote osprey
#

the card

#

but every card is still gonna check the input they receive from the class anyway

#

which is why i don't get why people make a class just as an intermediate between the input and the Card

swift crag
#

you'd have a class that detects which card you clicked on and tells it to start getting dragged around

timid oriole
#

currently I have this script setup

swift crag
#

!code

eternal falconBOT
timid oriole
#

ty

remote osprey
#

But I have many things that wait for a click besides cards

timid oriole
#

currently I have this script setup https://gdl.space/zurimequhe.cpp Now it works spawning that object randomly what if I want 5 different specefic spawn locations (Vector 3 points set by me) and not random numbers how would I do that

remote osprey
#

oh maybe implementing a common interfce between them?

swift crag
#

If many things care about mouse clicks, then yeah, you're going to have lots of checks that run every time the mouse gets clicked

#

I use InputActionReference with the new input system for basically everything

#

so I have code like this

#
    void OnEnable()
    {
        debugAction.action.performed += ToggleDebug;
    }

    void OnDisable()
    {
        debugAction.action.performed -= ToggleDebug;
    }
polar acorn
swift crag
#

If I have lots of classes that all care about the debug action being performed, then...yeah, I'll have lots of methods run when I perform the action

#

but that's a given

timid oriole
polar acorn
timid oriole
#

So like Vector 3 spawnlocation [] = {1, 3, 5, 2, 4, 6}?

swift crag
#

this syntax is very wrong, and, critically, those are not Vector3s

#

those are integers

#

Serialize a List<Vector3> and you can fill it with values from the inspector.

timid oriole
#

Vector 3 spawnlocation [] = new Vector3(1, 2, 5), Vector3(2, 5, 2}

timid oriole
#

Ill look into what that is

ivory bobcat
swift crag
remote osprey
timid oriole