#๐ปโcode-beginner
1 messages ยท Page 387 of 1
So what was that line again of your error?
so it's object reference not set to instance of an object
but I can access it from start() anf fixedupdate()
No, the line in your code. what was it
can you show the full code again? I missed the link
And component was never null?
no never
But you highlighted 231, is nto the error line?
wait its not obj.HandlePhaseAdvance(); throwing null ?
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()
And if you debug.log(obj) its throwing null?
oh okay because 231 in vs was showing was not it
yeah, it doesnt exist when i try to print it to debug
do you have more than one playeragent in the scene?
yeah sorry its not 231 i was a bit confused by the question but basically this works:
but this doesnt:
definitely not
Who is calling updatephase?
GameManager
And do you get the error always?
yes
so obj is never != null
no, I never set it to null or anything
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
this part works
I'm not sure there is a reference in the scene if its just a scriopt?
this is how you call the updatephase everytime?
Can you show the full code of that gamemanager?
and Player is an object in the scene?
yes, Player is an object in th scene
and that player.getcomponent<player> is always working? or not
but the obj. thing still throws an error. weird setup there
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
But he is never going to instantiate it. its just there.
oh they mentioned ML agents thought maybe it creates copies?
Ahh yeh, that mgiht be a n issue if it handles those players by itself
havent used ml agents in a very long time ๐
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?
!code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
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
Can't help you unless you share the !code. How are we supposed to know what your game does?
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
yea i was about to send that
just waiting
I'd assume after 8 minutes you would have send it
oh u wre waiting for me
the code's too long im sending in parts
Not at all, just pointing it out
hey this seems valid does it not?
the error was at last line before i added the trail renderer but then the car's just stuck
!code share code in a paste site when its so much
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
now delete those massive chunks of code above
Are you getting any errors, abnormal or unwanted behaviors? If so, you should inform us.
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.
nothing in here calls WheelEffects()
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
i should remove unityeditor.callbacks?
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
strings.count - 1
yea i set it differently
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
to like 0 1
change to if (clickCount < string.count - 1)
I'm assuming the string collection is empty and that the first element doesn't exist thus index 0 threw a fit.
so the string being empty matters
strings is an array of strings right? not a string
Reminder that the initialized array would be overwritten by the inspector values - think of the values in code as simply default values.
i share the code where the velocity is getting clamped?
the empty ones
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
what๐ญ
index out of bound means you are trying to access some invalid index, elements in the array/list has nothing to do with that
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;
}
}
}
}
Show us the inspector for that component (the instance in the scene)
im done out
this is the end of the line isnt it i learnt what tables and stuff were on luau
Yeah...
whats the problem in that
it is outside the scope of the method
oh, yeah, shitty indentation. !code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I did it
here
should have used a paste site again.
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
'Large Blocks' ???
you could have formatted the code first ffs
sry im a bit newer to unity
go to the very last } on your code. Delete it then add it back. The code should reformat automatically. Then re post it
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
that's better
cant believe that this is valid unity code
if (this is type)```
this is crazy to me
That's not Unity, it's standard C#
and there is nothing 'crazy' about it.
if AnObject.Type could be AnotherType
This !ide does not look configured. Is it?
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
โข VS Code
โข JetBrains Rider
โข Other/None
Valid C# code *
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
C# should never have allowed the @ option to reuse keywords
i used it yesterday.. but for some other reason
string wavePattern = @"
.
. .
. .
. .
. .
. .
. .
. .
. .";```
something something literal verbatim string something something
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.
this can be used in abstract/derived classes to find out what class inherited from it
ive never used this and not known what type this was
usually to assign values Like an initializer
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
yeah, I see that. But using derived class in your abstract class is 100% a mistake
It could be useful to know if a deriving class inherits a specific interface
Yep, for example that's a pretty good use case
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
A similar keyword you might want to know about is base ๐
ohh.. i still use TryGets to see if my classes use interfaces ๐
When base is specified anywhere, the call points to a class/method that the inherited class implements
So that's somewhat related to this, where instead you specify something from this class specifically
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
This is a solid way
Dbug? ๐
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
Dbug
Compared to pattern matching this which checks on the calling class
ohhh!
yea ur completely right
Normally it's Debug.
it still is
An instance?
Hey does anyone know why my Visual Studio doesnt see the namespace?
I have installed the plugin and it works in editor
In this case your abstract class won't even compile unless you have an implementation for the derived class
Are you using Assembly Definitions?
What is that?
Oh.
What do you mean? It compiles fine
Granted, only Bar() had to be renamed as to not be ambiguous to its class
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
If you have it as is in one file. But say you need it for another project or something. Now AbstractFoo can't exist without Bar
That's true, you would need to have a valid reference to Bar
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
I usually do something like that for Random or something when using System and UnityEngine.
using Random = UnityEngine.Random;
using Random = System.Random;
Then Bar implements AbstractBar, and AbstractBar inherits from AbstractFoo
Nice and complex ๐
Normally I use System.Random for procedural generation.
Yes, I think as a rule of thumb you should not pattern match "down", and there is no reason to pattern match "up"
Are you sure you have relevant packages installed?
I think it's more valid for matching against possible interface implementations as Steven mentioned. Abstract classes are a bit weird to do here.
mhmmm.. i also do the Random = thing.. but when messing with my Custom Debug class.. my .Log function actually just calls Debug.Log soo... i can just use Debug as an alias and call my custom functions.. and still use unitys functions
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
the Post Processing plugin is installed, i dont think there are any more plugins to it
Yeah I know.
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
Okay..
!code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
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...
ur comparison should be if currentItemSO != GetComponent<Item>
lemme try
its just asking if the currentItem is not null in that example
no problem ๐ .. lol ya, sometimes it just takes an extra set of eyes
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...
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
Id rather use trigger if u need to animate only once
that too
either or.. main point having a parameter in the transition
ive heard that sometimes its a bit laggy when high-traffic
yeha i will try later
I want my door to open slowly when I use a co routine is that possible
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
well, this would set the door's position to [0, 90, 0] ...
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);
}
}
'''
also, it also wouldn't do anyting "slowly". it would wait 3 seconds and then instantly make the change
I meant rotate
ah I see
Would I need a lerp then to move it slowly?
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
Correct
I would have the start rotation then the end rotation then the duration it takes to get there I believe correct?
write out the code you're thinking of.

why not use the new input system
because new users have enough on their plate
it is appropriate to learn after you get a bit of experience
new input system is really easy to get into
just takes a few lines of code
there are multiple ways to use it and the complexity really is not necessary or helpful for a complete novice
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
i'm a big fan of the new input system, but it is's not the first priority for a novice
thats partially true i guess
idk, can you help me with that please
first of all whats your game? is it 3d? 2d? top down?
whats your goal
3d
okay well if that script works then its fine
its a basic movement script
try it and see the results
it works but it lags. idk if its because of the editor or my pc or because of my script
and what does "it lags" mean?
the game runs at a low framerate?
the character stutters?
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
What do you want exactly? Do you want to get the player from another component after the game has started?
Player player = Instantiate(playerPrefab);
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
If you have a single instance of a player, then a way of getting to the player is by making the player a singleton. See Singletons here: https://unity.huh.how/references
Calling Find is not a good way to get something
What does this bullet need specifically?
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
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
the player has a basebulletSpeed i need to access
not sure i'd singleton the actual player.. when u can just plop a reference somewhere
which is a float
Why is this on the player?
Why not on the bullet, or the weapon shooting it?
Sounds like something the weapon would assign when you shoot the bullet
its a stat with all the other things like speed, jump height
i guess its the editor because its working with lags and then sometimes there are less lags
Then perhaps you should spawn the bullet from the weapon, and assign its speed value from the weapon
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.
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
if im instantiating a bullet, is there anyway i can pass the variable through that?
Bullet bulletInstance = Instantiate(bulletPrefab, bulletStartingPosition.position, bulletStartingPosition.rotation);
bulletInstance.speed = bulletSpeed;```
this is how i do that stuff
instantiate the bullet, then call a public method on the bullet that "initializes" it, for example
if the bullet prefab has a Bullet.cs script u can just instantiate it as a Bullet
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
Windows almost crashed
both valid ways
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
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?
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
Are you passing the Bullet prefab or the script of the prefab through?
its both
its a prefab.. (that has a bullet script)
w/o the bullet script it wouldnt make sense to do it that way
lol.. def more complex than mine.. I usually dont structure mine in a way wheer I know i can directly assign instantiation methods... soo im a TryGet out junkie ๐
this is solid tho ๐
i need to write more code like that
Yeah, TryGet would have the other attribute
Ah my question is hided because of these huge code blocks sent here
u commonly use this. like that?
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
i always get reprimanded for useless this
yes, I've grown used to it because of analyzers and code enforcements
Code feels weird without it nowadays
good, then im in good company
if im using any property / variable of the script im working in i unconsciously add this.
I use rarely if it is more readable in specific cases. For instance a check of dead state: (!target.IsDead || !this.IsDead)
yes makes sense! ๐
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 ๐
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
i prefer to just write this.foo = foo any time a parameter corresponds directly to a field
https://gdl.space/enacidoten.cpp
- Do you suggest this structure and why?
i agree
// Instead of limited enums(64 max), using a string is prefered there
this is wrong
you can have billions of enum values
i wish method signature parameters would instantly become that
you're only limited to 64 distinct values if you're using "flag"-style enums
this.foo = that.foo would be epic syntax
Yes i meant the flag thing
how are you using a string for TargetTag, then..?
some kind of weird comma-separated list?
have you seen people that use Enums w/ string comparisons?
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
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") ?
TargetTag here is it's type. Like: Turret, BigTurret, LargeTurret
So i will use normal flags then
why is the turret type stored on an ITarget?
does this represent the kinds of turrets that are allowed to shoot at the target?
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.
Yessss but lets dont dive into that
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
like so
in that case a flags enum would be fine
As for using an interface: that sounds fine
so an enemy can only be shot at by a "Large turret" and not a "Big turret" or "Turret"?
that sounds wrong
ROY G BIV Flag System ๐
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
Forget about the implementation details -- tell me how your game is going to work
specifically the part where your turrets shoot at stuff
i wanna know 2
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?
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
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
That doesn't really matter. Every ally unit will say it's on the Ally team
The exact unit type doesn't matter here.
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?
Weird how is it gonna tell which target is an ally?
by asking it
no indentation doesnt matter unless you use the shorthand if and else statements without curly brackets
public Team GetTeam();
this would be in the interface
Even then, indentation is irrelevant
It's not that the block is indented. It's that it's in a completely different place.
In the second screenshot, this block is inside of the if (player.HasKitchenObject()) block
In the first, it is after the block
you should go back to code monkeys tutorial
So still, i will need an enum right? For best uh choice
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?
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?
Yeah unit types
If every targetable thing has health and a max health value, then yes, that must be part of the interface
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
I need help with UI's
I just coded everything over unity edito
and realized that it causes weird things in different screen sizes
If you want to receive help with your question, pelase share relevant !code and explain what you want to do
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Mhm? what does it have to do with my code though
I mean UI cause problems usually
main camera size etc. changes...
Is this not related to anything in your code? Then why did you ask it in this channel?
I think you want #๐ฒโui-ux
It is, okay nevermind lemme post the code
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);```
Do you have a CanvasScaler set up? It can mess with values
Canvas Scaler? Like scale with screen size?
yes, it is a default Unity component on the canvas
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
I've tried matching with adding extra X and Y's but when screen size changes they get ruined too
Then you need to multiply by the scale factor
how do I do that?
You can use Screen.width or Screen.height and divide by your reference value
the rect is measured in the local space of the transform
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.
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.
You cannot.
shite
If you have several colliders on one object, you need to split them up into multiple child objects
they are in children objects
is your component attached to a parent object with a Rigidbody, then?
all the capsules are meant are children of the root parent. i want the "ontriggerenter" to only be triggered by the box.
you can put different kinds of colliders on different layers
otherwise, you need to handle the trigger messages on the individual child objects
i'll try this first
cant you also colliders triggers avoid layers?
terribly written, apologies
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
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;
}
}
}
did you look at any of the errors at all
Post the errors
you can't just stop at "i saw an error"
Usually you'd tell us what those errors were
i did but i dont understand them
Post them
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)
chill for a min i have to copy it im not a machine
You haven't assigned the cameraTransform in the inspector.
You probably need to assign the camera transform variable of the player controller script in the inspector
yea but before it worked
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.
It probably defaulted back to null - happens sometimes when certain things are changed within a script
it doesn't matter if something used to work
clearly something has changed and now it doesn't work
rather than arguing with the error, read it and fix the problem
At least the error is nice enough to tell you what to do ๐
The error literally tells you exactly what to do
Which part of what was suggested are you having issues with?
I. dont. Know. How. To. Do. that
Do you know how to drag the camera into the field in the player controller script via inspector?
wait
i dont find it, can you please help me
Show your hierarchy
wait
Where should I learn Unity for 2D game dev? All of the official unity tutorials are all 3D.
windows dont want to screenshot it. i hate my pc
win+shift+s
oh wow my script didnt show me the camera transform before because my pc is loading forever
now i saw the camera transform
wait
One of your objects in your scene (the hierarchy) has got the player controller component that's supposed to be referencing a camera but is no longer doing so. Select that object and drag the camera into it's field.
I didn't say to press ctrl-S
windows key, shift key, S key
i pressed win shift s do you think i cannot read or smt
honestly yes
because if your game saved when you did that you hit ctrl s
not win+shift+s
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
IT WANTED TO SAVE IT. I KNOW WHAT I PRESSED
One of two things happened:
- You pressed Ctrl instead of Windows
- There is no second thing that's what happened
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
I think this PC might be infected with PEBKAC
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
you think you are very funny right
It's a real thing, and it happens from time to time . . .
i know what pebkac means now and no its not my fault
your code, or the screenshot tool...?
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
It's not that bad.
every time i try to find an answer here some people say its my fault. Just leave me alone when u dont have to say anything useful for me. Just help me or say I dont know how to fix but not "its your fault"
to be frank, you have given us no reason to believe it's not just user error
the screenshot tool
and yes, I've had issues where the screenshot tool decides to disappear until I restart
i literally wrote the reason 3 times or more
I never used coding tutorials. I just set up Unity with Visual Studio and I was off. I looked at the Scripting API's and the forums from time to time and I learned pretty quick.
yeah its pretty straight forward
easy for me to get lost though
It's not too hard if you know what you're doing.
facts
Everything is fine and enjoyable until i get stuck doing something
And then motivation and everything goes away 
Oh also, not to talk about people criticizing and never giving credits to what you made for hours and just complaining
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
Everything is fine and enjoyable until I get a stupid frickin NullReferenceException! 
You pretty much oscillate between "I can do anything" and "I can't do anything"
Exactly;-;
For real.
Uhh, I never bothered you to begin with or said anything was your fault. I merely commented on a message (that was from someone else). I've no idea of your struggles . . .
Struggling with UI now:/
A lot of the time when I have an issue peple are like just use unity learn
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.
Oh my god happened so much times
If it is periodic you can use coroutine, if continuous you can also use update
I swear when i wake up the next day I can almost always find the issue within a few minutes its crazy
Facts.
Is that action periodic like filling up a can when I input ?
I think so
depends, 1 unit each tick -> use coroutine, some amount each frame -> update
But both ways are valid anyway, whatever makes more sense
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
i do the SetActive route
if im setting the transform to be the container anyway.. might as well just keep it there
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?
you can drop a new instance
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
or if your objects have a state, or a lot of logic switching parents might be easier
I see
for your drop though couldn't you just simply enable gravity and collider?
Then disable when you pick up
When you drop a gun it is basically a mesh, when you pick it up it has weapon logic with ammo state for example
^ 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
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
ya, i destroy the pickup
But if you have a game where you can pick up a chest with its inventory you would probably want to keep it until you drop it somewhere else. So depends on the project
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.)
Yeah I currently have a flashlight with a pickup and drop by using flashlight.transform.SetParent(emptyHolder); flashlight.transform.position = emptyHolder.transform.position;
Set it once with chained conditional operators and evaluate later with enum flags
so need need for the transform after the set parent?
Do a float array and each unlock is an index. Increase the index one every unlock. Check if the xp/level is greater than the value at the current index.
One if statement
the issue is althoguht I set it as a parent it doesn't mean its gonna be the position of the empty item equip
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?
I was referring to the dude not wanting to evaluate if statements when accessing weapon availability state.
ah okay
Interesting approach. I like it.
We need to see the raycast and debug code
I'll be perfectly honest, I didn't really understand that. ๐ฆ
Oh ok uh well Ill be back then i gotta take a shower
" I need a double cheeseburger and fries "
" Okay sir, please pull around to the window "
" Alright, gotta go get my oil changed first, brb "
Okay, so just figuring this out in my head, but could I do something like.......(this would happen during a 'level up' screen, where the game in the background it paused)....... (pseudo) for i=0 to levelFloatValue; i++) { weapon[i].unlocked = true }
weapon[] would be an array of weapon Scriptable Objects
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
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. ๐
sorry, meant to go to #๐โweb
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 }
Yeah I like that. Seems very elegant to me ๐
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
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. ?
it'd be a bit different but yea basically weapons[weaponIndex].Unlock();
public string weaponName;
public Sprite weaponSprite;
public bool isUnlocked;```
Yeah, cool stuff. Thanks for the input guys, really helpful ๐
@summer stump
you'll just have to adapt it to ur games specifics
Yeah, got a solid foundation to work from so that's awesome ๐
Sorry, had to step away. Spawns ideas are perfect though.
Glad to spark it off haha
Not a problem dude, your initial idea started it all. ๐
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.
Sounds good to me so far
wave spawner type inventory
Sorry just joining in
Can the player only have one weapon at a time? Or do they just unlock weapons as they level up?
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
They unlock weapons as they level up, but they can only change weapons at the level up screen. So if they wanted if they've unlocked 10 weapons, they can go back to weapon 1 any time they level up. I figured it would add a bit more variety as people tend to like different weapons etc.
Yes, that's basically what I'm doing, but the player gets to choose the weapon they want from their list of unlocked weapons until the next time they level up.
Shouldnt be to hard to implement honestly
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)
Yeah I think it's all figured out now tbh, thanks to spawn and Aethenosity ๐
Thats good theyre pretty smart guys
Yuh huh. lol.
i need to do my own weapon selection system.. currently u just have all the weapons
but it took me longer than i care to admit to do the scrollwheel selection.. and not have it jump entire indexes
U using the old or new input system?
both but on the mousewheel (old)
problem was my mouse wheel delta would change multiple increments at once
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]
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
ohhh sounds fancy.. like micro scrolls? software designed indents is what comes to mind..
ctx: https://youtu.be/Q76dMggUH1M?si=p7XVN7jditoYpVSW&t=144
I don't know how it translates into unity but iirc, each wheel 'click' equates to 3 lines of text in a wordprocessor/webage by default, it can be changed, but not many people know about it.
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.
i need help calling a function from main.js ```html
<script>type="module" src="main.js"</script>
"bceause it used transforms" is...very vague
uh maybe in webgl using their jslib interop
no idea what you're trying to do here
or how it relates to unity
Oh I know, that was all that I was told. Sincerely. lol
you'll have to point me to this exchange
yea im using unity webgl
I tried using .jslib file i read about on the docs but when i try to call it directly from the .jslib plugin it says that it cannot find the method im trying to call although names match
Oh it was months and months (maybe even a couple of years) ago.
make sure you've read everything here
https://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html
i did, even went through it multiple times trying to figure out why it cannot find the method although it exists in main.js
i suspect you've forgotten the finer details of why it was wrong, then
tbh I wasn't even asking a question about the weapon switching, it was something else in the script that was giving me headaches.
Can you show the code you used?
going to have to share more of the setup
alright give me a moment
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;
}
1, you likely want to yield INSIDE the while loop
2, see this https://unity.huh.how/lerp/wrong-lerp
main.js
export var loaded = false; // this is re-assinged throughout the code
function hasLoaded() {
return loaded;
}
JavascriptHook.jslib
var hook = {
Loaded: function() {
return hasLoaded();
},
};
mergeInto(LibraryManager.library, hook);
c# script
[DllImport("__Internal")]
private static extern bool Loaded();
It certainly can get to the end value. The third parameter, when 1, will return the second parameter
Oh, got deleted
Where do you actually call the js function?
Yeah, I realised how wrong I was when you mentioned where the yield went. I still have a massive blind spot for that. lol.
void Start()
That is not really helpful
Show the actual code
The most important part of the issue has not been shown yet
void Start() {
Debug.Log(Loaded());
}
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
Are you following https://docs.unity3d.com/Manual/web-interacting-browser-js-to-unity.html ?
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"
yes and i went through it multiple times
since I use external libraries in my main.js file, so i need to use import
Ohh for simple stuff I tested worked ok (mostly showing more ingame info on the webpage)
but never used modules yes, I should actually do more WebGL stuff. It's been a while.. I've been doing another JS interop with c# through asp.net core.. I kinda hate Js ngl, but the best stuff for web is JS lol
can't you just use that to call the file with the modules ?
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
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
yeah apparently this has been asked on the forums but no reply threads
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!
Ah ok, sorry
I haven't been paying attention to the broader context of this discussion, but you could probably just swap over to CommonJS module syntax to resolve that particular error
ive been software developing for around 4 years now, since 2020, this year is my first time using javascript. and my god ive never seen a problem that trial and error does not solve
interop between multiple languages makes things more fun
you get a lot of extra...~mystery factor~
yeah I'm not a fan of js .
I have to do lots of interop of asp.net and it aint fun lol
I love JS a little too much. Never knowing just what it's doing with my code under the hood makes me feel alive
is interop really the only solution for this?
does it differ alot from vite?
thats what im using atm
for your project? idk what you're doing
I use interop because its the only way c# can interact with JS when doing ASP.net (web developement c#)
i mean has anyone really got this problem before?
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"
ok reverse list doesnt work
should i make array of arrays to determine x of largest numbers in array not larger than y
First image is with data filled out. Before runtime. Second is of runtime. Third is after runtime.
Removes all of the values. That code shouldn't even be running since wavesTillVariation wasn't ever changed.
why do you need to use OnValidate here at all?
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.
this looks like runtime logic
OnValidate isn't even going to run at all in the built game
i will look into that, thank you for your time
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
Because when I am setting the data on waves, I am setting them in the inspector and before runtime.
So what?
I would set up wave templates in the inspector
and then use those to create "real" waves at runtime
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
wave templates?
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
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.
Explain what your game is actually going to do.
No implementation details at all: just gameplay
hello! how can i change thhe ambient color in rendersettings in script? do i use the ambientSkyColor ?
thanks
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.
Okay, so at regular intervals, you compute a new "wave variation", and the "wave variation" tells you what to spawn in each wave
yes
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?
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
no, only monobehaviours receive unity messages like Update, OnDisable, Awake, etc
Only if it's a Unity object that has an OnDisable message
(ScriptableObject can recieve those as well!)
i hope, at least
ah yeah, i should have been more specific since SOs receive some of those too (not Update though)
Hmm. Do I have any options on when I can unsubscribe listeners for basic objects?
an OnDisable method on a plain old C# class means absolutely nothing to Unity
Like an ondestroy or smth
explain what you are actually doing here
it is referenced by some UnityEngine.Object (likely a component), so why not use that object's OnDisable or OnDestroy to call some method on the object that cannot receive those messages
you might need to listen to something like Application.quitting or SceneManager.activeSceneChanged. It depends on what your intent is here
I have a plain object with listeners and I dont know when to disconenct/unsubscribe them since I dont have an OnDisable
Why do you need to unsubscribe?
isnt not unsubscribing bad?
It depends on the lifecycle of your object.
We can't answer your question without knowing what you're doing.
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.
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.
Oh, so you want to hand-author each one of these wave variations?
Yep
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(?)
see Praetor's messages again -- they explain when you must make sure you've unsubscribed
but how is OnDisable being called there
so all of these Executors are responsible for inserting text into one big description area?
oh its leftover code. its incorrect
i tried to make array of lists but instead it made list of arrays?
they only invoke the string
new List<string>[0]
You can manually call "OnDisable" here when you stop showing the UI element.
But it would be more normal to use IDisposable and call your function Dispose() instead.
But yes it's not necessary if this thing is not outlived by the CharacterStatsUI.
However - is that a static event?
it is
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
Ah I can definitely work something out
Yes, that would create an array of lists
An array with size 0 by the way
so it can't actually hold anything
this is an array of lists.
A list of arrays would be List<string[]>
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.
ah ok i confused code order
There is something like OnParticleHit that you can use
May be more what you are looking for
I dont really want to test what the particles hit, i have a circle collider on the object and i want to check for collisions with that
I am confused. Where do particles even come into play then. The object just HAS a particle system as a component as well as a collider and script?
And you want to detect collisions?
testing for collisions between what two things?
hello guyes how can i make the player to climb any thing i need the script pls
This is way too vague to answer in any meaningful way.
The Three Commandments of OnCollisionEnter:
- Thou Shalt have a 3D Collider on each object
- Thou Shalt not tick
isTriggeron either of them - Thou Shalt have a non-kinematic 3D Rigidbody on at least one of them
credit: digiholic
(non-kinematic Rigidbody)
Im in 2D, but the equivalent of this is on both objects
I had the trigger one in my clipboard and had to modify it haha. Forgot that
Im very confused
transform.position += Vector3.up
Now you are climbing
Then it should work
Show code
What does the particle system have to do with anything, is my question?
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)
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");
}
ok but the code doesn't really matter until we talk about what it is you want to detect the collision between
the bombExplosionPrefab and an enemy, it is instantiated and then whatever it is touching i want it to run code
If you're doing a bomb - a collider isn't really what I would use anyway. generally a bomb would be handled via something like Physics2D.OverlapCircleAll
assuming it just explodes instantly and you want to know what it touched
exactly that
You want this then: https://docs.unity3d.com/ScriptReference/Physics2D.OverlapCircleAll.html
don't put a collider on the explosion prefab
Ok thank you i will try
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?
store it in a visual element
Notice all the examples saving them in variables.
ahh uquery.. I use c# ones
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
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?
does it have collisions like particle system ?
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. ๐
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
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.
yeah you're right its all GPU based
I was just hoping unity made a node for it or something lol
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.
how instant is your Firethough ?
Imo the casting would probably be the best feeling for a firethrower
grow the size and distance of spherecast with deltaTime
I could scale the cone based on the throw speed I guess. I don't think spherecast would work tbh (bullet hell type game), so any enemies surrounding the player would burst into flames.
how so? the size would small at the barel
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
dont multiply your mouse inputs by time.deltaTime. ever
what would you use instead
none, just dont use it
If I put the pivot point at the 'pointy' end of the cone and scale from there pretty quickly (the throw is pretty quick anyway). Could also cut off the pointy end so it's more of a tapered cylinder.
yeah whatever works
I just find Colliders clunky
is this for first person you are doing a lot of strange stuff..
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);
}
}
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.
well yeah just gotta tone down "mouseSensitivity" now
raycasts are quite efficent
sorry i tried chatgpt because im not that good at coding yet, but im learning
not a good way to start as beginner. my advice is to actually start from the basics.
Look at the links pinned on this chhanel
set it to 50.0f
no i mean im learning not with chatgpt. Im learning for real
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.
I mean its obvious the script was bad, I'm just saying. You dont have to convince me otherwise lol
also you would have to check your pivots are even correct cause the code is already wonky, add ontop of that possibility of Pivot being further than you think
i never tried to convince you otherwise
anything besides raycast, use nonalloc version and you will see its pretty good compared to putting rigidbody on anything that needs to be involved in a collision
dont "over-optimize" where you don't need to
Okay cool. Yeah at the moment I do have the rigidbodies on the enemies, but have been thinking about switching the rb's over to the bullets as I think in the later game there will be fewer bullets than enemies by far, and I do have some 'static' enemies where the rb's are only on there to provide collisions.
I'd say for bullet hell optimizations def look into pooling if you haven't already done so
Oh yeah, literally everything is pooled so far. lol.
I'm even using For loops instead of foreach because apparently they're very slightly more efficient. lol.
Why?
Obsessing over performance lol.
thats crazy lol
Could you give me an example where the performance plays a huge role then?
Which shitty youtuber told you this so I can hate them
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.
It was actually someone in here. lol. I asked the question.
How to make a timer that activates a function?(pls help)
did you bother googling that ?
Well, do you have a specific example of a foreach loop beeing much better than an ordinary one?
yes
"how to make a timer in unity"
"how to call a function in unity"
I think I was able to find quite a few. You might have checked them all already, do they contain wrong information?
Nope. lol. But, tbh it kinda makes sense in my head that a foreach would be slightly (even less than 1ms) less efficient due to the creation of a variable etc.
If anyone's interested........
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. ๐
I mean, it is indeed more efficient. But this performance difference is surely small enough for you to simply ignore it
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
It's not even close to 1ms. You should definitely profile and start to see how little this matters. I wish more people would. Right now I could add a for loop that iterates 100k times every frame and no one would notice.
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:
Oh yeah it probably is, but, still learning, so when I get more experience with these things I'll be able to make better judgement calls on what to/not to use etc. (if that makes any sense?)
what
nvm
huh ok
that was someone else. Also why did you put deltaTime back on the mouse ๐ค
it's right there..
you need to pay at least a little attention to the code you're copy-pasting from the internet
esp gpt
If you are struggling to get started, you should drop this and use !learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
i just wrote this one is from github
copied *
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.
i just wanted to see if it would at least work
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.
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 ๐
Still, I do suggest just setting up a blank scene and a test script where you use profiler.beginsample. keep it around so you can run small tests whenever. Just a note this isnt like an extensive test, there are libraries out there for actual testing. But you can be pretty confident if one code takes 4x longer than another for example.
Oh yeah I definitely will ๐
just started the unity essentials
how do i fix this error? its not rlly affecting my game but i would like to fix this
It's an internal unity error. Close any graph window (animator, shader graph, etc) and close then reopen unity
Then you can open those windows again
ok
would it be smart to get move input for running state and for walking state instead of just using that of walking state?
huh ? how are you doing it now?
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
Yeah its copied from cs and its predecessors like source games or quake.
I mean you can easily just reverse the logic your default walk is just sprint speed..
holding shift or whatever will turn into walk speed
bool walking = Input.GetKey(KeyCode.LeftShift)
float currentSpeed = walking ? walkSpeed : sprintSpeed
I did not know you could do this cl
i made a whole input action for it
oh the new input system right its different, just an example though..you just need a bool from the walking action ๐คทโโ๏ธ
yeahhh i get you thanks
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.
First step is to check which line is throwing the exception
the for loop
which line
for (int i = 0; i < inventorySlots.Length; i++) < this one?
Show the full error message
And that's line 11?
yeah
If that's line 11 then iventorySlots itself is null'
I cut some of the code out because it didn't feel necessary to send
yeah that's what im assuming is happening but I don't know why. in the inspector it clearly has 28 items
Since that's a serialized array field, the only way it would be null is if:
- You set it to null elsewhere in the code
OR - You created this component with
AddComponentand never populated the field
I think you're making a false assumption that the InventoryManager you're looking at in the inspector is the same one which is throwing this exception
You'll want to look at the full stack trace here
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
makes sense
thanks :)
Anyone know How I can make an online system or a good yt video that explains it?
"Online system" is pretty broad, but you might check out the pinned post in #archived-networking for some resources
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?
I see a lot of people leaving the input handling only for a single class.
I don't understand what this means
One class that receives the input and sends an event to other classes that care about that input type
it's a bit of indirection, but i don't see how this leads to
then every observer would receive the input
because then every observer would receive the input
And what does this mean?
unless you only had one gigantic OnInput event
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
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
this problem has nothing to do with having an "input manager" class
but why not have all that input checking be done on the Card class indirectly?
also, what is an input manager then?
doesn't it sound less efficient to have all of your cards individually ask the input system if the mouse has been clicked?
the class you're describing here #๐ปโcode-beginner message
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
uhh, not if i implement an interface that only tells when a click happens with a OnCLick method
okay, and who calls OnClick?
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
my point here is that you wouldn't have each card check for clicks at all
you'd have a class that detects which card you clicked on and tells it to start getting dragged around
currently I have this script setup
!code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
ty
But I have many things that wait for a click besides cards
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
oh maybe implementing a common interfce between them?
Your problem does not really make sense to me.
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;
}
Make a list of possible locations, roll a random number between 0 and the size of the list, get that spawn point out of the list, use that
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
Make an array of Vector 3s/Spawn locations?
Sure, or transforms or whatever else you're using to define a spawn location
So like Vector 3 spawnlocation [] = {1, 3, 5, 2, 4, 6}?
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.
Vector 3 spawnlocation [] = new Vector3(1, 2, 5), Vector3(2, 5, 2}
A list ah
Ill look into what that is
You'd need to assign the array an array object.
Transforms are nice because you can physically position your spawn points in the world.
so maybe something like
public class InputManager {
public OnClick () {
if CheckIfCardClicked() {
OnCardClicked();
}
if CheckIfPlayerClicked() {
OnPlayerClicked();
}
}
}
[SerializeField]GameObject spawnlocation [] = new Vector3(1, 2, 5), Vector3(2, 5, 2} u mean like that?