#💻┃code-beginner
1 messages · Page 725 of 1
rigidbody (kinematic I think) or translate, each has its pros and cons
if you mean timescale you can use unscaledDelta
I think... my game window was bugged. I closed "game" and "device simulator" and reopened "game" and now everything seems to be working.
maybe you didnt fully click in ?
as long as its working now though ig lol
I tried that but I can't seem to get it to work right. Currently this diamond shape spawns with its center at the position of the gun, but I want it to spawn so the tip is touching the gun. I tried moving it forward by adding the direction and a multiplier to the transform.position but the more the angle goes away from the horizontal the more out of whack the position gets
Thanks, this worked.
The animation of my character is slightly skewed though, so when I walk forwards it actually ends up walking about 20 degrees off from 12 o'clock
you'd have to show screenshots or videos of what you mean
it could be an issue with how your scene/control system is setup or it could be an issue with your character model
yeah thanks for everything 🙂
This is when holding W (ignore the random things in the scene, I'm doing some practice stuff for class)
oh like this type of thing is more of an offset , i thought you meant moving as in a character across or something
The character does rotate with the camera, but it's off
And it's the animation itself that moves the character, not any script I've made (which I don't like, but that's what we were taught thus far)
what is the origin of the diamond anyway? if its a sprite it would probably just be easier to make pivot at the tip then parent it to the muzzle object
do I set that in the editor somewhere or does it have to be in the code?
you can do either one, easier in the editor probably
I can change the sort point from center to pivot but I don't see where to define the point
sprite editor lets you change pivot of a sprite so if you want to add the tip instead it'd be easier
oh
I'm trying to edit the sprite in the prefab but its saying the asset is not editable
if you click the sprite and bring it the asset importer window you should see sprite editor.. unless its Unitys sprite then idk how lol
how to fix this?
trees with black edges, I know that the problem is in the material, but I don't understand a bit
this is a code channel..
maybe copy it and modify the copy
Hi! I’m trying to get all levels from Word Collect APK. I only need the level data in JSON or text format, no graphics or sounds. Could someone extract it?
and where should I write about the questions here?
mb
#1391720450752516147 is probably best
that did it, thanks!
thanks
can I invoke a unity event that was defined in another script?
directly invoking it doesn't seem to work, is there a way to do it?
yea UnityEvents can
event fields cannot
an event can only be invoked in the owning class but a UnityEvent is just a class that re creates event functionality so no restriction.
how do I do that then? do I have to use like a get method to get a reference to the event from the script that defines it?
that's what I'm doing but the event is not getting invoked
put a log and see if thats called
or use a ✨ debugger
I put a print in the method that is supposed to get called but it does not print, and I have subscribed it correctly in the editor
wait do I have to subscribe it in both scripts?
if you use a debugger and have breakpoints where you Invoke and what you expect to be called then you can actually know whats happening
a subscription in the inspector or in code is fine
If you don't get a log, that line never runs
I mean, I have it subscribed for the script that creates it but not for the second script that also invokes it
You're going to need to be more specific
trace your code and see where it goes wrong 💫 debugger
Like, what is it subscribed to? What is the "other" script in this context?
And yes, the debugger will let you step through every line one at a time
that's not the issue, I wanted to know how to correctly invoke a unity event from a script that does not define that event
I told you
you must have some other problem or be mistaken
use a debugger to debug this properly instead
.Invoke
no I mean, I am most certainly doing it incorrectly
Then share some !code if needed
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
Is the event on the correct instance that you expect?
if the subscription is done in the inspector, is it still valid when you Invoke the event?
if I just do eventName.Invoke() in another script it tells me eventName does not exist in the current context
you need to retrieve it from the instance of the class...
you need a reference to it
GetComponent<MyCoolClass>().myDumbEvent.Invoke();
script doesnt magically know about it
what are you doing 😆
Well, does eventName exist in that context?
remember when we did the thing where we put each debuff into its own class? I'm trying to have one of them invoke an event
then you need a reference to the object instance that has an event
share some code if you need further help because you seem very confused
so that connection needs to be hardcoded, I was hoping to avoid that somehow
ok one sec
if you want some event that exists "globally" then use a static event:
public static event Action<Debuff> OnDebuffAdded;
Here you should avoid UnityEvent because there is no benefit
maybe my whole approach is just dumb
I think you forgot about object instances
in this case, the buff is supposed to change the basic attack to a different one while the buff lasts, so I thought it would be best to call the unity event and have the attack script listen to that and switch attack types when it happens
something like this could make sense
e.g.
public void AddDebuff(Debuff debuff)
{
debuffs.Add(debuff);
debuff.OnActivate += OnDebuffActivated;
debuff.OnDeactivate += OnDebuffDeactivated;
}
in this example we subscribe to the events on that specific instance
presuming these are something like event Action<Debuff>
using UnityEngine;
using UnityEngine.Events;
public class CounterShockEffect : EffectObject
{
public override EffectAlignment EffectAlignment { get; } = EffectAlignment.Buff;
public override EffectType EffectType { get; } = EffectType.CounterShock;
public override int EffectAuthorityLevel { get; } = 1;
public override float EffectDuration { get; set; } = 1;
public UnityEvent onCounterShockOn;
public UnityEvent onCounterShockOff;
public CounterShockEffect(float effectDuration = 1)
{
EffectDuration = effectDuration;
}
public override void StartEffect(MonoBehaviour mono)
{
onCounterShockOn.Invoke();
}
public override void StopEffect()
{
onCounterShockOff.Invoke();
}
}
``` this is the debuff class I currently have with the non working invokes
Ill point out that UnityEvent is a worse replacement for real c# events
where do you subscribe to these events though?
it's subscribed in the skill script, since I was hoping to just call it by name
CounterShockEffect effect = new();
effect.onCounterShockOn.Invoke();
anyway you seem to only care about half of what I say
that's not true
its poor design also to invoke some objects event externally
ok
(which is why event prevents this wow who knew!)
Look just understand that you can subscribe to an event ON some instance, and then invoke that instances OWN event.
If you want it to not belong to a single instance but be "global" use static.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/static
the problem is that I have trouble wrapping my head around how to apply half of what you say to my situation
If you want to respond to these events on single instances of the effect, then do not use static
but then you need to have a reference to the effect to sub and invoke its events
if you want to do something when a specific button is clicked, we sub to THAT buttons on click event right?
Same exact concept
yeah I get that
then do it correctly or realise what you want is different to what you have created soo far
but rn i dont actually understand what you want
the effect class has the event so why is it hard to access and use?
and where are you calling StartEffect and StopEffect, and where do you sub to these unity events?
I can't subscribe the event in the effect class because it's not attached to an object, and I can't use GetComponent because it's not a monobehavior, that's why I was trying to define the event elsewhere
Then your design if flawed
yes
If you can't access an instance then wtf is going on
Share how you add an effect to the player/thing
The class doesn't have to be "attached to an game object"
you can use events on non mono behaviour classes just fine
this is in the EffectController
public EffectObject StartEffect(EffectType effectType = EffectType.None, int effectPower = 1, float effectDuration = 0f, int effectFrequency = 0)
{
EffectObject effect = null;
switch (effectType)
{
case EffectType.Burn:
effect = new BurnEffect(damageController, effectPower, effectDuration, effectFrequency);
break;
case EffectType.Slow:
effect = new SlowEffect(characterController2D, effectPower, effectDuration);
break;
case EffectType.Quick:
effect = new QuickEffect(weaponController, effectPower, effectDuration);
break;
case EffectType.AspdDown:
effect = new QuickEffect(weaponController, effectPower, effectDuration);
break;
case EffectType.AtkUp:
effect = new AtkUpEffect(weaponController, effectPower, effectDuration);
break;
case EffectType.DefUp:
effect = new DefUpEffect(damageController, effectPower, effectDuration);
break;
case EffectType.ResUp:
effect = new ResUpEffect(damageController, effectPower, effectDuration);
break;
}
if (effect != null)
{
EffectsList.Add(effect);
effect.StartEffect(this);
OnEffectReceived.Invoke(effectType);
}
return effect;
}
public void StopEffect(EffectObject effect)
{
EffectType effectType = effect.EffectType;
effect.StopEffect();
EffectsList.Remove(effect);
// Check if this was the last effect of its type
if (!EffectsList.Exists(entry => entry.EffectType == effect.EffectType))
{
OnEffectEnded.Invoke(effectType);
}
}```
holy fuck
what is this abomination
now imagine you have 50 effect types
in your game
Okay, so, let's step back. Let's discuss the design of one effect you want and how that might be done. How about you give us an example of one thing you want to do, and what affect it is supposed to have?
I asked here how to best do this and this is what I was told to do
how told you to make such structure
I don't think so, I think you didn't quite understand what was suggested
it's a mess
it works so leave it as is right now to not confuse yourself
ok so this is a buff that changes the basic attack to a different kind of attack while its active
which I am doing by checking a bool in the attack script
Okay, so, what is "an attack" and how is it changed? Pick one effect, whatever one you like the most. Start with a working implementation of one, then add more on it
attack is currently this
public void AttackOne(Vector3 attackDirection)
{
//Visuals
//Anims
onLiskarmAttackOne.Invoke();
GameObject bullet;
if (ultimateAttackEnabled)
{
print("enabled");
bullet = Instantiate(ultimateAttackPrefab, projectileSpawnerTransform.position, gunHandTransform.rotation);
UltimateAttackScript ultimateAttackScript = bullet.GetComponent<UltimateAttackScript>();
ultimateAttackScript.speed = attackSpeed;
ultimateAttackScript.direction = attackDirection;
ultimateAttackScript.damage = attackDamage;
ultimateAttackScript.shieldCollider = shieldCollider;
ultimateAttackScript.shooterCollider = ownCollider;
}
else
{
bullet = Instantiate(bulletPrefab, projectileSpawnerTransform.position, gunHandTransform.rotation);
BulletScript bulletScript = bullet.GetComponent<BulletScript>();
bulletScript.speed = attackSpeed;
bulletScript.direction = attackDirection;
bulletScript.damage = attackDamage;
bulletScript.shieldCollider = shieldCollider;
bulletScript.shooterCollider = ownCollider;
}
}```
We aren't looking at code yet. We're talking concepts
Just things like "It changes the prefab that gets spawned" or "it changes some numbers in a script" is what would be sufficient
it changes the prefab yeah
Okay, so, the end result is you want a different prefab if a specific effect is active
yes
Okay, and what is the source of the effects? What causes one to be applied?
the prefab colliding with a player
Prefabs can't collide with anything, they're files
So, it's like a power-up in the world, and when the player touches it, it changes their attack?
it happens on a key press
What happens on a key press?
wait
the prefab changing effect happens on a key press
when the instantiated object collides with a player it can apply effects too
I have a spherical player rigidbody that rotates in midair when it jumps via directly setting its angular velocity; however, because it rotates, when it bounces off the ground it moves in the direction of its rotation, and I don't want this to happen
Does anyone know how to achieve this? I tried storing its angular velocity then setting it to 0 in OnCollisionEnter(), then restoring it in OnCollisionExit(), but that didn't seem to work
constation the position on the rb component?
It's happening because of friction
if you want to avoid it, you can set up zero friction physics materials
I tried setting the player's physics material friction values (both dynamic and static, individually and together) to 0, but the player still rolled on impact (and removing friction made the ball travel faster than it rolls, making the movement look fake)
UPDATE: Setting dynamic friction to 0 and setting "Friction Combine" to "Minimum" achieves an effect close to what I want, but due to the lack of friction the player doesn't roll, instead sliding along the ground
These facts in mind, how can I prevent the player from rolling when landing due to angular momentum without removing its ability to roll?
You'd have to use the contact modification API if you want to change how the collision affects the objects in that way
hello, what is this?:
!input
To set Active Input Handling, go to:
Project Settings > Player > Active Input Handling
• Input Manager (Old): Use the original Input settings.
• Input System Package (New): Uses the new input system package.
• Both: Use both systems.
Hello. I'm making a multiplayer game using FishNet and having issues with OnCollisionEnter not triggering. I'm using a debug statement right at the beginning of it, so it's not getting returned - it's just not triggering at all. My object it's on has a Rigidbody, with 5 colliders as children. It triggers when it hits another object that is a Rigidbody, but not on anything else with a collider. There are no tags or layers being used on anything - it's all set to default. I tried adding a collider to the Parent and that changed nothing. I confirmed no colliders are triggers. I tested with a mesh collider, a sphere collider, and a box collider, and none of those matter - the only thing that matters is if it has a rigidbody on it. I also confirmed the Rigidbody isn't Kinematic.
Oh I also tried changing Collision Detection to all the other types and that didn't work either. I also tried putting the OnCollisionEnter script on one of the child objects with a collider and that didn't work either.
im trying to add an item to my inventory through a function that I can call whenever I want but I dont know how to convert my item class to a visual element
What's the error say?
So it looks like arrayOfItems is an array of type Item. You cannot store an Item in a string
I was just trying all sorts of stuff
you don't have a string in Item for name or something ?
What do you want itemString to store
What value do you want in there
uh I think I want it to be a image
you tested it without network connection?
If you want it to be an image why is the variable of type string
idk I was trying random things
So maybe you should think about what you actually want and ask that question
this is what it should be
Okay, and what does that error say
Okay, so, what VisualElement do you want to put there?
So you probably want a VisualElement that can display an image
I'm not sure if UIElements is part of #🧰┃ui-toolkit or if it's a different thing entirely, but there's probably some sort of image component
tbh If you're new probably easier to make prefab for ugui and spawn those in
UITK you can do
var img = new Image(){
sprite = mysprite
};```
but there is more to it if you want it interactive
I'll see if I can manage that. Unfortunately, it's kinda hard to do.
server could be turning it kinematic
oh I forgot I already have this but I want to add an item through code during runtime
for testing purposes
The inspector doesn't say they are, but I'm not sure that's actually accurate.
it should be but you can put a log to double check
Looks like you just need to set that variable to the Item you want
I tried setting CurrentItem.texture2d but CurrentItem wont show up in my function as autofill
and its red
texture2D isn't a UIElement
but it looks like whatever this is sets the icon to the texture2D on whatever item you set it to
so that's probably what you want
What does the error say if you move your mouse over it?
it doesnt currently exist in the context
my code throws an error I assume when the is no clip? how to I test for a clip
if (animator.GetCurrentAnimatorClipInfo(0)[0].clip)
IndexOutOfRangeException: Index was outside the bounds of the array.
you can do something like this
public void Add(Item item){
img = new UnityEngine.UIElements.Image()
{
image = item.texture2d;
};
visualElement.Add(img);
}```
maybe ? anim.GetCurrentAnimatorClipInfo(0).Length
what are you trying to do btw?
It should be an array where you'd be able to use the length member as suggested above
https://docs.unity3d.com/ScriptReference/Animator.GetCurrentAnimatorClipInfo.html
the thing is, it works most of the time, it only happens occasionally
still can't figure out why
I'm assuming either a reference wasn't properly setup or is modified during runtime etc
& is the layer index always 0 ?
I check immediately after changing the animation, maybe some lag?
I am controlling animation purely through code
so I need the length to know how long to wait before changing again
maybe not
var clipInfo = animator.GetCurrentAnimatorClipInfo(0);
if(clipInfo.Length < 1)
{
Debug.LogError($"Clip Info had a length less than 1. Check the Animator.", animator);
}```
Clicking the message once should highlight the animator object. You should verify that it's got a clip
im gonna take a break, my brain is fried
if you plan on adding different maps, here is my suggestion
When you figure out chunk placing, place your obstacles where you want, then tag them with what specific object they are. Then make a script that places those obstacles into the specific tagged areas, you'll need to add prefab references
seems to have fixed it... it was intermittent but it hasn't failed
I don't fully understand something. I've tried to make changes to a prefab in the inspector and in the code. The prefab's scripts that change something aren't reflected in the inspector (serialized sections). The code in scripts doesn't seem to update the prefab? Also, if I try to change the rotation of the prefab in the inspector it just appears in the game at its rotation that it had from the start. Totally confused here.
Hi. Does anyone know if RigidBody2D.linearVelocity is multiplied by delta time (fixed or not) by default?
the serialized values of a serialized field take priority over a field initializer. a field initializer on a serialized field is basically just a defaut used when the component is created or reset
it is
Thanks!
I can already tell there is going to be an issue with the orientation of this sprite and having to transform it (as a projectile) first according to where an enemy is pointing, but also according to the sprite itself's orientation. It's going to get weird.
Sprite "laser projectile" is pointing ---> so "up" is it moving up but pointed in that direction (to the right). Solved it with space.world (and rotating it) because the player is always pointing straight up, but once they aren't... gets weird.
There are pins in the channel for resources to look at
if i do kind of
Update(){
tmp.text = "a";
}
does the canvas know that it doesnt actually change every time and redraw every thing each frame? like how the canvas detect change of an element
Am I wrong in thinking that a sprite (such as a weapon projectile) might need to be pointed a certain way to make your life easier (before you even use it in the project) or I am just confusing myself.
You are correct in thinking that
Generally you want the "forward" direction of the sprite to either be facing right or up.
The you can always use transform.right or transform.up in your code
Not really a code question though
Yea but a code issue
Been having a hell of a time juggling trying to transform / move the sprite in the right direction because of its orientation
Not sure if I am confusing myself
Yeah it's best if all of your sprites use the same convention for forward, either up or right but consistent between all of them
If you want to share your code and some screenshots and explain what's going wrong, someone might be able to help with your particular issue.
Well I had to rotate it and use space.world to get a right-facing sprite to fire "up" in game (shouldn't be using world axis obviously yea). I spent way too long trying to figure out what I should do. Now I feel like if I have AI flying around the scene pointing in any directions am I going to have a massive headache getting the rotation of the "laser" going forward from where they are pointing because the sprite has to be rotated before "firing"? I could be making this more complicate than it is.
Guys, my game is on Unity 6.2 and im currently trying to learn to use UI Toolkit. I've been searching on google for a while but i cant find the answer so i will ask here. Which one is better for a story game with levels, 1 UI Document for each scene, or 1 UI Document for each game feature? I've been thinking of doing 1 for each game feature, but i'm not sure cuz im afraid of the performance for having multiple UI Document component in a scene.
Scratch that I think I found one solution
this is a code channel. perhaps you want to ask about uitk in the #🧰┃ui-toolkit channel
yeah, my mistake sorry, i've sent the question there too
You're definitely overcomplicating it.
The transform.Rotate thing in Start is kind of a red flag
Had to force it
You can set the rotation when you call Instantiate
does anyone have a tutorial for making a 2d card game multiplayer? I only seem to see stuff that uses a player object in real time, rather than mirroring a board and having turns
Most of the time rotation seems to change the axis with it. Up becomes to the left because of rotation.
Transform.Translate in the default mode works in the object's local space. If "up becomes left" that actually just means what you are calling "up" is left in your prefab
Which means either your sprite is rotated wrongly in the original image or you did something in the prefab with child objects to achieve that
Sharing some screenshots of your prefab would help
Yea it's like this
With tool handle rotation set to "local"
Yeah pretty clear that "forward" is right for this sprite
So if you moved it "up" it would appear to be going left
So I should just transform right all the time and consider it forward?
You need to either edit the sprite or start using right instead of up
So I did transform.Translate(Vector2.right * projectileMoveSpeed * Time.deltaTime); and Instantiate(blueLaserPrefab, transform.position, Quaternion.Euler(0,0,90)); -- seems to work if that's proper I guess I will see later
for now I assume that as long as I do that it will always "come out the correct end orientated correctly", until I test it in other ways lol
can I make a Spherecast start around the chacter so the character would be in the middle and it would detect things behind?
if I made the sphere big enough
do you want overlap maybe?
What do you mean by "detect things behind"?
I think he wants to start his sphere cast behind his character
I think I am going to put a big collider on and set it to Trigger, then I can detect all around
That could work we do not know what you want to achieve specifically
I am an trying to put an agro detection on the enemy so they can detect then agro on player
it kinda works with casting, in 4 directions, but that seems inefficient and it leaves blind spots
thank you!
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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 Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
Does anyone know a video for complete beginners that explains every single code line?
You've asked this before, and the answer is the same : there is no such thing.
Thought someone might have something
nor would it be useful
Nothing has changed since a few days ago.
https://hastebin.skyra.pw/aqululaxuq.csharp
https://hastebin.skyra.pw/evuyowibaq.csharp
https://hastebin.skyra.pw/nidiweqema.pgsql
What's supposed to happen:
on button click create a new gameobject based off a prefab.
Add the gameobject to the scrollview's content. Assign the right Sprite depending on which button was clicked.
What happens:
Creates new object at the right place but doesn't change the Sprite renderer's sprite
You were already redirected to !learn and the resources pinned in #💻┃code-beginner. One would hope you took the initiative and started going through that instead of waiting to hope someone would answer your impossible questions a few days later. 🤷♂️
I went through it and don't understand it
Then those are the questions you ask help for. Asking for a dictionary for "every line of code" isn't going to be useful.
Why are you using SpriteRenderers at all? Isn't this a UI thing?
For UI you use the UnityEngine.UI.Image component
your Button already has an Image on it
that's what you should be referencing
By default they get one anyway
unless you deleted it
its not supposed to change the button's image its supposed to change the image the newly made object has
which is what? Can you show the hierarchy of the prefab?
it was this. Instead of the Rawimage in the hirarchy it had the sprite renderer. just added that to try what you suggested
definitely you should be using Image, not SpriteRenderer
oki imma try it
tried it with a image and it still doesnt set the Sprite correctly :/
you're looking at the prefab
look at the spawned object at runtime
Sounds like your code isn't actually running
Have you tried any debugging? Where's your console window?
This code is calling loadPage on the prefab, no?
you would need to call it on the actual instance in the scene
I also don't even see where you are Instantiating the prefab at all
it gets instantiated in 'public void addPageToDeck(); in FightingDeckManager
you're instantiating it and then ignoring the instance entirely
Also why is this code so overcomplicated:
GameObject page2Add = pagePrefab;
pagesInDeck.Add(e);
objectsInDeck.Add(page2Add);
Instantiate(objectsInDeck[pagesInDeck.Count - 1],this.transform.GetChild(0).GetChild(0).GetChild(0)); //child 1 is scroll view obj child 2 is viewport child3 is content
objectsInDeck[pagesInDeck.Count - 1].transform.position = Vector3.zero;
page2Add.GetComponent<PagePrefabScript>().loadPage(e);```
you have like 4 different ways here of referring to the same object
this.transform.GetChild(0).GetChild(0).GetChild(0)
And this is the stuff of nightmares^
but yeah this is the main issue
Transform redudantTransform = this.transform.GetComponent<Transform>();
because I usually try to get it to work and then clean up the code afterwards
nuttin wrong w/ that
imo no point in spending 5 minutes on figuring out how to call it smoother if it doesnt even work in the first place
ya, but on the flip side.. if its overly confusing ur doing urself a disservice trying to figure out what went wrong..
Transform content = this.transform.GetChild(0).GetChild(0).GetChild(0);
GameObject page2Add = Instantiate(pagePrefab, content);```
if you insist on the GetChild ladder you can still just clarify it using variables..
it'd make the *rest* of the code more readible
objectsInDeck[pagesInDeck.Count - 1].GetComponent<PagePrefabScript>().loadPage(e);
changed it to refer to this instead and it's still not changing it :/
mmm sure ill change it once ive got this figured out
yea u good.. just trying to be helpful.. with tidbits
am I referencing the right thing? is Image.Sprite the sourceimage?
yourImage.sprite but yea
did you change it to grab the Instantiated clone rather than the prefab?
use some Debugs / Console to slowly troubleshoot it piece by piece
use .name to log the objects and make sure they are what u believe they are.. and so on
so, I was about to try the check sphere, but it doesn't provide the transform that was hit...
I think so?
im referencing the objct in the List
if u need the colliders https://docs.unity3d.com/ScriptReference/Physics.OverlapSphere.html u can use this instead
the switch isn't working properly .-. its not a technical issue
thanks, got it working!
I'm failing to understand why it's Debugging "Null" when the element is hard coded into the different Pages
well.. ur working on that script it is an issue..
null reference stop the code from running
soo... if u get that error anything left in that script isnt gonna work
in the instance yes
but I have that script on different objects
the other elements are implemented
and still don't return the right element
well ur debug of Null is ur major hint..
if its null.. u need to figure out why its null..
so.. back-track that variable
debug.. it more
find out when it becomes null.. or rather... why its null..
instead of what u expect it to be
hm oki
why not try using the debugger in rider?
And if you want help with it you'll have to show what you're trying to log. The screenshot cuts out the relevant part
woops youre right didnt realize
it's 'Debug.Log(localPage.getElement())
ill check some stuff and come back if i cnat figure it out
ty
I implemented the elementpage incorrectly. Wasn't inherited properly so it instead created a new one while getElement was checking the inherited variable "element"
agro is working well...
I found my issue. I had an early return statement in OnCollisionEnter (I thought I was debug.log'ing before it) that was returning if rb.linearVelocity.magnitude was too low. I had to change it to collision.relativeVelocity.magnitude.
How can you get the quaternion z position rotation and store that in a variable?
Sorry rotation
why do you want to just store z of quaternion 🤔
As an example
quaternion != euler
anyway
they are just floats
Yea I'm just saying I need what is here (0,0,here) and store it in thisfloat.
So I can take that and add 90 to it etc
when in doubt, check the docs
https://docs.unity3d.com/ScriptReference/Quaternion.Euler.html
You want either:
- to store the up vector of your object (as Vector3)
- to store the rotation around the z axis as a float, which you can get using Vector3.SignedAngle
- Keep track of the rotation yourself in a float variable, and use that to drive the rotation instead of trying to read it back from the Transform
There, that seems to work
Sorry for confusion in terms, my brain was working like the sound of a dial-up modem off the hook.
Is it possible to add a reference to a prefab's child object in a Sciptable Object?
No you can only reference the asset
Is it possible to detect when a raycast has hit an object from the perspective of the object? Like, I know you could do an OnCollisionEnter for phyics collisions, is there any equivalent for that for raycasts?
No. Whatever does the raycasting must message the object
I am trying to get a direction to go an object using moveDirection = (agroTransform.position - transform.position) however, the movement speed is affected the further away the two are... I have tried dividing by distance, but is there a way to simply get the direction to an object so I can multiply it by my speed setting?
My code isnt working i don't know whats wrong with it
I Just want my flappy bird to flap but the space key isnt doing anything
https://screenshot.help
but also 👇
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
Nvm figured it out✌🏽
void Update()
{
if (isVitaminShot && targetEnemy.hasFoundEnemy)
{
Vector3 directionToEnemy = targetEnemy.enemy.transform.position - transform.position;
directionToEnemy.y = 0;
directionToEnemy.Normalize(); // Ensure the direction is a unit vector
// Move the bullet forward in the new direction
transform.rotation = Quaternion.LookRotation(directionToEnemy);
transform.Translate(Vector3.forward * (bulletSpeed / 10f) * Time.deltaTime);
targetEnemy.hasFoundEnemy = false;
}
transform.Translate(Vector3.forward * bulletSpeed * Time.deltaTime);
}
does anyone know why my bullet is teleporting when targetEnemy.hasFoundEnemy is true?
i want it to smoothly rotate towards the enemy for a frame
why do you translate it a second time that frame?
sorry this is actually the current version
void Update()
{
if (isVitaminShot && targetEnemy.hasFoundEnemy)
{
Vector3 directionToEnemy = targetEnemy.enemy.transform.position - transform.position;
directionToEnemy.y = 0;
directionToEnemy.Normalize(); // Ensure the direction is a unit vector
// Move the bullet forward in the new direction
transform.rotation = Quaternion.LookRotation(directionToEnemy);
bulletSpeed /= 10;
targetEnemy.hasFoundEnemy = false;
}
transform.Translate(Vector3.forward * bulletSpeed * Time.deltaTime);
}
"Smoothly rotate for a frame" is a contradiction. One frame can have one change in rotation. If you want to do it smoothly you have to do it over multiple frames
i see i see
this is how it looks like
@keen dew
I like your lighting and the overall aesthetic!
thanks!
coming to steam soon
Good luck!
I would like to ask this question I asked yesterday again, as it continues to stump me
Since making that post, I have tried:
- Using rigidbody constraints to prevent the undesired movement (could not find a good way to store/reapply both angular momentum and direction after the constraints were removed)
- Changing the player's physics material to remove all friction to prevent the undesired movement (worked, but ruined various other aspects of the player's movement)
Things I have considered but haven't tried yet, mainly because they sound overly-complicated for the problem I'm trying to solve: - Using contact modification to remove friction considerations from the player when it lands (I cannot find any form of documentation or tutorials for the contact modification API)
- Making a "landing only" physics material that I swap out the regular one for one frame every time the player lands (sounds promising, but also sounds like it will create a lot of problems)
Could I ask for advice on what to do here?
Maybe assign the rotation a value going towards to wanted rotation. Where argument A would be your current rotation, B the desired rotation and C being the maximum delta etc
https://docs.unity3d.com/ScriptReference/Quaternion.RotateTowards.html
Adjust the friction when player leaves ground then set it back once they've returned to the ground
Also have you tried rotating via setting transform.rotation rather than setting the angular velocity?
How? Do I change the physics material? Do I swap out the physics material for a new one for a frame? Is there some other way of changing friction I don't know about?
is there a way for me and my friend to work on our game in real time?
Currently my player is physics-based and rolls because force is applied to it
I heard that you shouldn't alter angular velocity often, but I feel as though implementing two different rotation systems to correct an edge case like this to be overcomplicating things
Is it generally advised to not used Gameobject.find ?
yep its not quick but useful in some edge cases or for debugging easier
i checked my code multiple times i dont think its the code
its cost is the same but ideally you design things better to not need it
sure
Find("Player (Clone)") 🙂
do the clones have the code inside them?
also
"PipiMove"?
Can't you just reference it and change the value?
I think I just fixed it
I remove all friction from the player in OnCollisionExit() and restore it in OnCollisionStay()
Just after that in OnCollisionStay(), I check if the player isn't moving horizontally but does have angular velocity, and if they are, I remove all their angular velocity
Thank you for your help! :)
Show !code
Does the new bot not work with commands in the middle of lines any more?
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
There it is
Any idea how I can simulate tire heat?
like is there any decent equations for the heat generated by friction?
one heat to one friction
fr?
Isn't friction like, definitionally energy lost due to heat
no sir
Yeah but since force requires energy and energy can't be created, the counter force must come from the heat energy
The speed loss comes from some amount of kinetic energy converting into heat
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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 see what you're saying but honestly im not sure I didnt take physics lol
Try again
Oh, it's way too big. Yeah, throw it in a paste site
So what's the problem
#💻┃code-beginner message
you should use a site designed for code so it isn't a pain in the ass to read
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
AI code 🤢
You have the debug log there, does it ever show that isGrounded is false?
Then the ground check is wrong
You'll have to do more debugging
What is the groundCheck object set to, what is the value of groundCheckDistance, what is the groundLayer set to
What does the debug ray show
Ok first of all, the console isn't supposed to show anything. Read the comment above the DrawRay call
groundCheck is supposed to be set to the object that detects the ground, not the ground itself
Hello there, have been learning programming with c# on my own, trying to stay away from chatgpt and discord as much as possible but I have hit one of those no go topics. I am looking into LINQ and all I can find is basic tutorials nothing in depth. I can ask chatgpt but I don't want to as it doesn't help with critical thinking and push us to look for answers.
So here is my question:
I have a list with a class I have created. I will be getting string input from the user and I want to look throught each x string in the array and find the best matches possible from the given string (so not exact match, best matches). Example: Array {"MyPotatos","TheApples","RottenPotatos", "I need help with potatos"} Input from user = "Potatos". From array look through strings and find best matches to user input. Result: "MyPotatos","RottenPotatos", "I need help with potatos"
please someone help people
I am becoming a bit desparate
Stop copy-pasting code from AI without even reading it and follow a proper course
I'm getting the following warning, even on a new, empty scene
CommandBuffer: built-in render texture type 3 not found while executing (SetRenderTarget depth buffer) UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
Normal for editor errors to happen, it won't affect your game
Hello, i have a problem with my Android build, when i make a release build, no button is working but in the développement build, every button works thank you
Hello, new to the group and just started learning C# and Unity. Are there any recommended free courses/YT channels to learn the basics? TIA!
anyone have any idea why my inspector is suddenly displaying stuff weird?
is there a way to make it so [SerializeField] only happens if a variable in the script is a certain value? I want different values to display in the inspector depending on what type of object it is. ie TireType.Pacejka or TireType.Brush
that stuff happens at runtime, whereas the serialization happens beforehand, and can be editted outside of runtime
sounds like you're thinking of how ie spriterenderers or images show different fields based on type?
that's done with custom property drawers i believe, that isn't selective serialization
it's all still serialized, just not all shown
being serialized and being shown in the inspector are 2 different things that happen to mostly overlap
brother what? it happens in both editor time and runtime
public enum TireType
{
Pacejka,
Brush
}
public class TireModel : MonoBehavior
{
//this variable will be assigned in the inspector by the user
public TireType tireType;
//only show this variable in the inspector when tireType is Brush
public float contactPatch;
public float muz;//only show this variable when the tireType is Pacejka
}
Yes exactly
how do I edit what is shown in the inspector?
with a custom property drawer
Thank you now I can do some looking on the docs!
forgive me then im a moron
and i figured my thing out, commenting the headers out calmed it down
found these forums from google as well, linking other resources
https://discussions.unity.com/t/show-and-hide-serialized-class-fields-based-on-enum-values/766243
https://discussions.unity.com/t/need-help-customizing-inspector-based-on-enum-value/815123
oh wow
that second link has some shit i can just copy paste over pretty much
dope
Thank you @naive pawn you in here putting in work all the time.
i am not understanding why i cannot assign these objects in the prefab to the my SO ShipData's mount system
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
ngl chris that gets to be a real pita 😛
i figured that was a small enough chunk an image would be fine, guess not
it makes my job a lot easier
representing text as text is a lot better than representing text as an image
(for the small chunks you're trying to show you could also use the inline code part, but this works too)
for large chunks that should be in a paste site, yes
kinda looks like the mount location field is grayed out?
(why make it an Object though)
GameObjects and Transforms are 1:1
huh come to think of it, that could be why - it'd be ambiguous what you're trying to assign
thats why i tried to drill down into the setter and make it possible to use a GO or a Transform explicitly
that could also be from trying to assign a scene object into an asset context (very unfortunate weird message)
what object are you trying to assign onto?
ah wait, a ShipData SO, right?
im not sure you can reference children of a prefab like that..
it's kinda like the scene object into asset context thing
hmm, how to best store the information then
would it be possible to just store it all as a component on the prefab?
yeah so i should just make the ShipData an MB instead of an SO, basically?
yeah
if that makes sense for the data you need to store - i don't have full context of what you have the SO doing
well its supposed to be data on the ship in question. name, nation, type, level requirement, what weapon mounts it has for primary/secondary guns, where the transform to instantiate whatever guns get equipped goes, the rotational limits for each turret location, etc
yeah that probably could be on the prefab
off topic but im pretty proud of how my blendering has come together so far too 😛
alr thx for the help, my roommate is nagging me to go to the gas station for him, ill ponder as i go and try to convert it over and see how much better it goes afterwards
anyone know a decent forumula to calculate tire temp? i seen the ones on google just curious if anyone has used one they know works
@languid pagoda
no idea but youre making me curious about the nature ofyour project lol - racing?
yes
well really just vehicle physics
i have no intention of actually making a game
ah neat - i assume youre aiming to drill down pretty deep into simulation then??
yes for the most part
have a custom multi model wheel collider
can use pacejka or brush tire model using raycasts for suspension
that sounds pretty awesome, but i know nothing about tire models
https://paste.mod.gg/tkekcmnhsknf/0 how can i make sure that the player doesn't get bounced up whenever the paltform moves down or up? (one reminder, the reason why i am not using parenting because that would make that the player unable to follow the platform despite being a child object to it because the platform is kinematic and the player id dynamic, even whe full kinematic contacts, it wont work)
A tool for sharing your source code with the world!
How are you actually applying the force onto the character controller when it is on the platform?
I’m not applying any force. When the player is standing on the platform I just move their Rigidbody2D by the platform’s frame‐to‐frame delta:
Vector2 delta = next - currentPos;
if (IsOnTop(rider))
rider.position += delta; // i.e., direct reposition, not AddForce/velocity```
So there’s no force being applied, just manual translation.
Well, ignoring the fact that alone is a red flag, then of course it will make your player "float" at the top because the frame before the platform goes down it has moved your character up one frame by the movement delta. And because your character's falling has acceleration, it's "disconnecting" from the platform.
Anyway, the solution is likely in needing to flip the authority on what has control over your character. The platform shouldn't be "moving" the rider at all, it should only care about it's current velocity. The rider is the one that should be detecting that it is on a moving platfom and then applying the velocity of that platform to it's combined velocity/input from the player.
I get what you mean about flipping the authority, I’ve tried the ‘platform just provides velocity, and the rider applies it’ approach a bunch of times. The problem I kept hitting is that because my platform is kinematic and my player is dynamic, simply parenting the player to the platform doesn’t work, the player won’t inherit the movement, even with useFullKinematicContacts enabled. That’s why I ended up trying to directly add the delta to the rider’s position
Switching the authority has nothing to do with parenting the player. That should never be a thing.
Right now your platform is actively overriding the position of the thing that is on it, that authority.
Your platform should be a dumb object that has no idea anything is on it. It simply goes about moving along it's assigned route.
The actual smart object, your character, is the one that determines it is on a moving platform and takes the velocity of that platform into account when determine it's current frame velocity by factoring it into whatever other velocities are being applied - such as your input.
The platform can have it a property Velocity that it continually updates as it moves about, which your character can use.
so, make a different script something like PlatformRider for the PLayer?
Maybe generalize it more. A script to detect what the player is in contact with, reference its velocity for its own velocity updates
all surfaces, even mobs maybe, expose their velocity. if player stands on something, it will interpret its velocity as a product of input + surface its on. most surfaces wont move and have velocity of zero
or player have another script that checks if it's on the platform?
yet i am afraid that the player woudl still bounce up anyways
Then that would be an issue with your implementation
But the theory does, in fact work
well i am thinking on changing up the platform script first
so is there a script i can find and maybe a tutorial that have like a separate script that detects when the player is on the platform?
If there is, I'm not going to be the one to look and find it for you 🤷♂️
well already looking for it
This video implements it the same way you have, and suffers from the same issue. Their bandaid fix is to increase the gravity scale so that you don't notice the disconnecting because the player essentially speed falls back into the platform.
Sure, until you find another edge case where it conflicts and are back here asking how to work around that one.
ok
well the first steps seems to be going alright
anyone know why something like this would happen? my graph will not appear unless I adjust the transparency first. But the color is already set its not like its got 0 transparency
https://paste.ofcode.org/HfwU4FP28pEZVzgwBi8apc
huh wasn't even an issue with my code i deleted the object and recreated it and now its fine ?
lol
this is for help writing code in unity
This Awake() method is called whenever a new weapon is picked up. It is specific to each weapon. Is this okay?
I dont see why not
It's "ok" in the sense that it probably works but it's not really following any best practices. It looks like those scripts should be singletons or there should be one (or more) top level managers for handling those things
I'm fairly new to Unity. By top level manager, do you mean a sort of "manager" script that would handle that stuff?
exactly, attached to a gameobject placed somewhere in the scene
Either a singleton that you can use to access those components anywhere (Manager.CamRecoil for example) without having each individual component find the components separately, or a manager that creates the weapons and assigns the references to the weapons at that point
for instance you can see my GameManager object that has a few management components attached to it in the inspector
What's the benefit of using a GameManager like that? The components I'm referencing are being used in that same script, so would using a GameManager make it more complicated?
Because I then have to create more references
hey guys. i just tried the 3D Beginner Game: Roll-a-Ball tutorial on unity website to get a hang of the engine. In the player input, this warning is shown. And i cant move my player. Do i need to fix this warning first?
this is the script so far
No you'd need less references. Now you have 4 references to the other scripts in each weapon. With a manager you'd have 1 reference in each weapon (to the manager) and all the references to the other scripts would be in the manager
Have the weapons already attached to the player and connect through inspector
Disable what is not currently picked up
I'm trying to create a system where the player can pick up and discard weapons
Yes this is my solution for that
You've typoed OnMove
I'm a bit confused now as to how I reference the components from the GameManager object?
Like the CamRecoilScript
You make serialized fields and drag the references in the inspector
Serialized fields in the weapons script?
No in the manager
Oooh, so I don't need to do the FindObjectWithTag ?
Then in the weapon script GlobalReferences.Instance.Camrecoil
Yes the entire point is to avoid using the Find* methods
Right, that makes sense. Thank you
I go the route of manual initialisation so I can provide dependencies then as args and avoid both find and static fields
dependency injection frameworks exist for unity that can do this for you
Hi, I'm a bit new to using the profiler; what does these mean (and why is EditorLoop taking the most Time ms)? I'm on deep profiling mode and these seems to be Unity builtins or some sort?
additionally the game is stuck at ~60fps despite the target fps being set to 90 (tried disabling vsync whenever possible)
In editor the editor executes things each frame which is why its included in the profiler
PlayerLoop is for the game
14ms to render canvases is pretty high
well i'm not sure what's causing it tbh
All I'm seeing is extension/builtin calls
How much stuff is in your canvas? Are you making use of sub canvases?
We can see canvas render has the 14ms time
When a single object in a canvas is made dirty the whole canvas has to be rebuilt
You can use canvas components within a canvas (add them to child objects) to optimise what gets rebuilt
it won't require too much rewrites, right?
(the canvas child is just Transform and RectTransform iirc)
its easy
If you have a fuck ton of things in 1 canvas its going to increase its redraw cost greatly
e.g. add canvas component to "Game View"
may also require a graphic raycaster component if input stops working
Hopefully you know what things in your canvas get changed a lot so you can judge best where to have a "sub canvas"
The point is to prevent things that dont change very often or at all from being re built
well I'd say having to redraw the entire HUD and other stuff just because it triggered a hit particle would make sense that it'd be costly
Does this make sense though?
do I just do it like this?
yep and now its children will be rebuilt by this canvas and its seperated from any parent canvas
Don't slap them everywhere but where it makes sense
do I need to update any scripts for that to actually happen or the editor will just take care of it?
alr thanks
welp at least it's throttled by smth else now 
the consequence of not admitting defeat to DOTween
keep it up 🧠
Well I'm having issue with lookups now
// Navigate forward
while (true)
{
// Get the next timestamp in the list
Timestamp timestamp = null;
foreach (Timestamp storyboardTimestamp in Storyboard.Timestamps)
{
if (timestampType.ID == storyboardTimestamp.ID)
{
timestamp = storyboardTimestamp;
break;
}
}
this is a bad search method for something done on high volume of calls, but it's too simple to be able to think of anything better 
At a surface level, use a dictionary instead of a list. "Get the next timestamp" suggests maybe they could be ordered so that it could just pick the next index
ID is an enum, if that helps
Cool that works in a dictionary still
or if the data is paired then make them structs so you don't need to search for the pair every time
Tried it, it breaks (oor it's just I'm too incompetent to mess with this >.>)
it's the latter I'm afraid
I don't have a good grasp on how dictionary lookups would work
- last time I have dictionaries in other places, it has a pretty high self ms in profiler for some reason
It should be better when you have many things in a collection
do I keep the timestamp = null part
If there's more than 1 or 2 items in the collection it's pretty much guaranteed to be faster than iterating through a list
unless there's a custom hashing function and it's royally messed up
Well iirc Storyboard.Timestamps is sorted chronologically (since it's a rhythm game)
so grouping it by IDs sometimes makes me think it's not the best idea
So if you're picking the next timestamp you can store the current one's index and then pick index + 1
when I implement it, it either; 1. Executes by type instead of time (i.e Rotates THEN transforms, instead of doing both in parallel) or 2. It stops moving altogether
https://paste.ofcode.org/c3kr6PwD3Eh9sUj6GN5Lnj
@worn bay This is an example of some Dictionary lookup code that i happened to have just written
I shouldve put that in a pastecode sorry
@keen dew
Values and where wtf
Ok but that just means you're doing something wrong
can't know what it is without seeing the code
https://paste.ofcode.org/eg8C8Cpkbu3y7mQakxTka (the entire file in question)
So which is the problem with this code?
hi,I don't really know how to ask my question, but I've been trying to make AI bots that are animated and shoot at the player(military bots) for 7 days and I can't achieve what I want, I would want to know if there are tutorials that would help me or if there are other solutions, it's my first time trying to do this and it's always nice to have some documentation to start with
the Advance method
Yes but you said that you run into either of these two problems. Which one of these two is the problem with this code?
well this is before the implementation attempt so neither :v
(I reverted them)
I'll probably go check somewhere in my git tree if I kept it somewhere
if (!CurrentValues.TryGetValue(timestampType.ID, out float value))
{
continue;
}
if (!Storyboard.TimestampsByType.TryGetValue(timestampType, out var timestampList) || timestampList.Count == 0)
{
continue;
}
while (timestampList.Count > 0)
{
var timestamp = timestampList[0];
something like this
I can't figure out what to fix here
NullReferenceException: Object reference not set to an instance of an object UnityEditor.Graphs.Edge.WakeUp () (at <d7deb46552984aa294977920c8085e3d>:0) UnityEditor.Graphs.Graph.DoWakeUpEdges (System.Collections.Generic.List1[T] inEdges, System.Collections.Generic.List1[T] ok, System.Collections.Generic.List1[T] error, System.Boolean inEdgesUsedToBeValid) (at <d7deb46552984aa294977920c8085e3d>:0)
UnityEditor.Graphs.Graph.WakeUpEdges (System.Boolean clearSlotEdges) (at <d7deb46552984aa294977920c8085e3d>:0)
UnityEditor.Graphs.Graph.WakeUp (System.Boolean force) (at <d7deb46552984aa294977920c8085e3d>:0)
UnityEditor.Graphs.Graph.WakeUp () (at <d7deb46552984aa294977920c8085e3d>:0)
UnityEditor.Graphs.Graph.OnEnable () (at <d7deb46552984aa294977920c8085e3d>:0)`
iirc this one gives the second bug I described (objects stop moving altogether)
may you share the script?
I don't even know what script is causing it
when I double click it doesn't take me to a script
That's a Unity editor bug. You can ignore it . . .
well, thats annoying!
I hate seeing errors 🙁
your scripts are running all fine?
ya, game still runs
yeah ignore it then
does anyone here know a lot about using scriptable objects?
If you have a question just ask it and if someone knows they'll answer
I currently have a badly designed buff debuff system that I'm supposed to replace by a system using scriptable objects but I can't figure out how to do that in a way that actually improves my situation
i wanted to create an if statement that checks the amount of instances of a specific gameobject currently present in the scene and if they are higher than a set amount, it would disable the player's ability to spawn more, but apparently you can't just use >/</= signs for gameobjects
Well you can use them for the count of gameobjects but that's a bad way to do it
Make a variable that tracks how many have been spawned
Why is that a bad way to do it?
probably because it's more laborious to make it account for the gameobject deletion
like it can count but you also need to make a separate instruction to decrease the counter when the gameobject is deleted?
would you happen to know an argument for that?
i could make a list i guess
Basically the same reason why using Find is bad, because information about the state of the game should not be derived from the scene but there should be an authoritative source about the state
Counting the gameobjects is fine but arguably better would be to have something else track them. Store them in a list and remove them from there the same time they're destroyed
this is why game managers are important - they should be this source of authority, tracking what needs to be tracked and keeping tallies on anything that will be useful or needed for calculations
ideally being the thing that issues the command to create whatever it may be that youre tracking, and such
alternatively, does someone know a good way to invoke a unity event in a different script?
single source of authority and all that
Also if you're just counting the instances that are in the scene it implies that there's nothing controlling what can spawn the instances and they can just be created willy-nilly. Having just one thing be responsible for spawning and destroying the objects pays in the long run
i tried looking at the manual but i don't really see anything that could help me track instances.
what i could do is considering that the spawning is managed by an if statement that is declared by a keyboard input, i could make a new list, then add a line that adds 1 to the list inside the if statement that manages input.
I was thinking you'd store the instances in the list because it can be useful for managing them also in other ways
but if you just want to keep count then make an int and ++ it
i mean i could do that i guess.. i'm not familiar with managing objects and instances scripting wise. unity tutorial makes them feel almost like classes
And again it's fine to just count the objects if you don't want to completely redesign the code structure. Just remember to check the count with >= etc instead of the collection itself
Typically, anything you need to track is stored in a collection. That collection is a field on a class. This same class is where you control when and how that object is spawned . . .
you mean Unity.Collections?
No, a collection, as in an array, list, stack, queue, etc. . .
You can expose a method on this different script that calls the UnityEvent . . .
ok, i made a private List<GameObject> dogCounter = new(); and added a dogCounter.Add(gameObject); in the if statement. now, this is all on a PlayerController monobehaviour, but what removes the game object in question is inside another monobehaviour called DestroyOutOfBounds. can monobehaviours share commands or communicate with eachother? if not i will just add a timer that makes the list delete one item after the amount of time it takes for the object to go OOB and get deleted
Does anyone know how to actually sync up my health bars value to the value in my code?
rn it grabs the value from the slider but altering it in the code doesn't actually do anything and changing the healthSlider to be static kinda just breaks everything
my code for context --> https://paste.mod.gg/tqjrsjruhets/0
doesnt slider require a number from 0 to 1?
so if player health is 50 then slider should be 0.5
Classes are able to "speak to one another" if they have a reference to the class (they want to speak to). With a reference, you can access any public members: fields, properties, methods, etc., on that class . . .
o ya makes sense
ty king
It depends what numbers you set for min and max, but in their case, yes . . .
btw next time ask a question in one channel only 😉
cuz crossposting is against the rules
does anyone understand what this means? https://learn.microsoft.com/en-us/dotnet/csharp/misc/cs0176?f1url=%3FappId%3Droslyn%26k%3Dk(CS0176)
I'm not using static anywhere, my method is public override void StartEffect(MonoBehaviour mono) { Debug.Log("invoke event"); Debug.Log(mono); mono.FindAnyObjectByType<LiskarmSkillScript>().onCounterShockOn.Invoke(); }
and I get that error
In your code the type name is MonoBehaviour and instance reference is mono
so "cannot be accessed with mono; qualify it with MonoBehaviour instead"
is there any way to limit the find to only look in components attached to the character the find was called from?
I'm in EffectController and want to find a component in PlayerControllers, but when I have two of the same character, it finds the component in the other character instead of this one
You can use Transform.Find to search the GameObject's children by name . . .
it's not a child
Or GetComponentsInChildren to search for a component . . .
got it. made class public, gave it a reference in out of bounds script and added the line to remove 1
I don't get what this means then. How are the components attached to the character if not in the character itself or its children?
now i just need to understand how to block the input from instancing while the list is at 1 or higher
You should properly provide all the information instead of drip-feeding. It's hard to tell what you need with so little information . . .
its a complex project, I can't tell which information you need
I doubt you want to know all of it
but I can show you all of it if you want
I did post the screenshot of the hierarchy showing its a sibling
actually I can probably do something like parent.GetComponentInChildren
hmm it doesnt know parent
transform.parent
thanks that did it
If you want to avoid searching (using GetComponent), you can give each of the XXXControllers a reference to the script on the Controllers GameObject and give the script on the Controller GameObject a reference to each of the XXXController components . . .
wut
as good as an excercise that was, i found a much simpler way, just a cooldown using a bool and a cooldown float.
still, learning is important
unrelated to unity, but how do you disable in VS that thing that makes you replace a character instead of inserting a new character? like when it does that grey overlay over a character
push insert key on your keyboard
lifesaver
lol
iam beginner at coding, i know how to use functions, if statements, bools, gameObjects, Vector3 and Vector2, but i dont know what to learn now, what should i learn?
learn to make a game
What do you want to code?
If I rotate a transform, does the collider not rotate with it?
Will I get performance penalties as well when I overdo it?
why should I use Graphics.RenderMeshInstanced when Graphics.RenderMeshIndirect gives me much more flexibility?
It may because it could affect batching as each canvas is drawn on it's own
I see
there's stuff you can learn at !learn
If you say had a canvas on your parent for an inventory UI and no more then it would be good.
i dont want to learn multiple things at once
Nah this game has too much stuff in it 
you can look up c# tutorials and see what they have
that site has unity stuff, if you want to see what c# has other than if statements then you can check youtube or check the pins in this channel, theres some resources there too
I used the example of an inventory screen as if a user can interact with it then it may change a lot and this benefit from it's own canvas
If needed perhaps another canvas for say a grid of items could help but depends
so uh why can't I select my method from here
you have to drag the whole object into that field
probably because you put the file not the actual component
is there a better way to check for collisions with a polygon collider than Physics2D.OverlapCollider?
why is there a conflict here? I'm merging a branch into main, said branch doesn't have another definition for SampleScene.Unity
well, see what it says
the commandline or your ide's integration don't give you any more info whatsoever?
perhaps you deleted the file on that branch so the "conflict" is changes to sample scene VS deletion of sample scene.
You've got local changes to that scene file, the repository has changed to the scene file too.
Git can't figure out which changes should be applied over the other so you have to decide. Since you can't really text edit a scene file that easily, you'll probably just need to manually make whatever changes the upstream has in your scene, save it, then force push
if they merged some branch into theirs then "local" doesnt mean anything
if you had working copy changes that conflicted then a merge would just fail
hello! im trying to get into 3d developing with no experience with coding or developing as ive been inspired by TVGS who made the game schedule 1. Within unity what coding language do they use as im not experienced with coding at all and how would i be able to learn it?
C#, !learn and check the pins
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
I can't get my arrow to fly, it just stays
`
newArrow = Instantiate(arrow);
newArrow.transform.SetPositionAndRotation(arrow.transform.position, arrow.transform.rotation);
newArrow.SetActive(true);
private void FixedUpdate()
{
if (newArrow != null)
{
newArrow.GetComponent<Rigidbody>().AddForce(arrow.transform.forward * arrowSpeed, ForceMode.Impulse);
}
}
`
Instead of having this script apply force to your spawned arrow every frame, put a script on that object that gives itself force
still not working, it must be something with my object?
void FixedUpdate() { transform.GetComponent<Rigidbody>().AddForce(transform.forward * 20, ForceMode.Impulse); }
Possible, no idea what Network Rigidbody is doing
if (tireTemperature > ambientTemperature)
{
tireTemperature -= cooling * deltaTime;
if (tireTemperature < ambientTemperature)
tireTemperature = ambientTemperature;
}
// Heat from slip & load only when on ground
if (suspension.IsWheelOnGround)
{
// Slip magnitude: longitudinal slipRatio + lateral slipAngle (in radians)
float slipMag = Mathf.Abs(slipRatio) + Mathf.Abs(slipAngle) * Mathf.Deg2Rad;
slipMag = Mathf.Clamp(slipMag, 0f, 3f); // cap extremes to keep it stable
float loadN = suspension.fZ.magnitude; // normal force (N)
float mu = Mathf.Max(0f, tireData.frictionCoefficient); // friction scale
// Simple heating: proportional to mu * load * slip
float heatGain = heatingCoefficient * mu * loadN * slipMag;
if (heatGain > 0f)
tireTemperature += heatGain * deltaTime;
}
any idea how I can improve this? seems like no matter how much I play around with the coefficients i cant get the values consistent.
either is heats up way too fast or way to slow
if I remove it, the arrow disapears completely...
did you write the method correctly?
is this all in the same script?
this makes no sense..
no
if tireTemp > ambTemp.. then the nested if statement would never be true
maybe u didnt meant to nest it there
wdym, if the temp is greater than ambient it subtracts from it, then after that value is subtracted it could be less than ambient so it sets it back to ambient.
ya, but it runs in a single frame..
the NEXT frame when it loops back over..
think about it in terms of values.. and step thru it..
if u step thru it.. its never gonna run
maybe 1 single time
ahh
ur using it like a clamp
yes
no problem lol i was so confused
me too 🫠
im about to ditch it and try again anyways
i would.. if its taking consider amount of time to debug
it might be more cost efficient to redo it
I stripped it down, added a sphere, added a rigid body, added the script
void FixedUpdate() { Debug.Log("is fixed working ?" + Time.realtimeSinceStartup); transform.GetComponent<Rigidbody>().AddForce(transform.forward * 20, ForceMode.Impulse); }
and it works, so must be a problem with my arrow object
bro please use proper code tags.
ohh... and i also agree w/ u bout the car stufff
a cars sillhouette almost likely will be copyrighted/ legal issues
should I use FixedUpdate? or just Update
what are the propper tags?
void FixedUpdate()
{
Debug.Log("is fixed working ?" + Time.realtimeSinceStartup);
transform.GetComponent<Rigidbody>().AddForce(transform.forward * 20, ForceMode.Impulse);
}```
```csharp
/// code here.
^ this..
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
single ticks are for single lines
hi, when you make a unity game, how can you make it for pc and mobile?
for some reason the CS has to be in capital letters for me or it doesnt work
make two builds
might be confusing that with a line break...
definitely not the case
oh yeah nvm
do you have to make input action maps for player movement? also how do you know how to design the UI?
I'm just not smart
please do not crosspost
yea, those are the two caveats i would consider
ur inputs and ur ui
you can set them in the input manager
im not exactly sure how u could do that
thanks! solo dev, haven't shared much code before...
yes
yea i'd have to think about that.. im not all that well versed in the new input system tho
without changing the code, just a game thats identical but obviously different ways of controlling character
ok ill research it
i can help search around.. but thats all i can do
it's very easy with the new input system
can devs just make builds for any device?
thats what i was expecting
i have some expereience with new input system
im pretty sure thats 1 of the perks of the input system
just confirming, should I use FixedUpdate()? or just Update()
1 actionMap = multiple platforms
yes
yes pretty much and the input system should make this pretty flawless as for ui you're going to have to set the default selected device and then your controller will just work with the ui
using the same code?
fixedupdate since you''re using addforce
depends on what exactly you're doing probably
cool, that's what I found
wdym by "set the default selected device"?
yes my car controller works with a keyboard a controller and a steering wheel + pedals its the same code for all I just added more bindings in the action map
if you're targeting device specific features that wont work on other devices you'll have to adapt
is there features for the ui where you can just scale it depending on screen size
my mistake default selected ui item.
compounding forces like addforce shoudl be in fixed
while impulse forces can be done in update
yes
I just look for tutorials online
oh? I am using ForceMode.Impulse
newArrow.GetComponent<Rigidbody>().AddForce(arrow.transform.forward * arrowSpeed, ForceMode.Impulse);
yo russell.. ur values are probably way too high
ok thank you so much
u need really small decimal values
like coolingrate would be like .2f
heatingCoefficient should be even smaller like .0002f
I played with them a ton haha i couldn't really get anything that felt right let me try some more
oh wow yeah the heating was too high
i was using like 0.5
Treat coolingRate and heatingCoefficient as tuning knobs. Start super low, then bump up until it “feels” right
and i mean super low lol
since ur running possible +60fps
thats getting called in my physics substep, its being called 200 times every fixed update 😭
i havent done car mechanics in quite a while so im a bit rusty
but last time i did something lkke this was for losing airpressure
and it was a really small decimal
this kinda just broke my brain a little
f Unity is doing ~50 fixed updates per second → that’s 200 * 50 = 10,000 calls/sec. No wonder your tires are going nuclear 👀
u can use ur substep as a factor for ur values
tireTemperature += (heatGain / stepCount) * Time.fixedDeltaTime;
(heatGain / stepCount) shuld normalize it abit
that would give a value closer to what i was mentioning earlier.. like .000x
if (heatGain > 0f)
tireTemperature += heatGain * deltaTime;
deltaTime is defined as Time.fixedDeltaTime / 200(number of substeps).J shouldnt that be enough?
Ill give it a try now tho
Thanks for your advice!
ohh so u are already doing that
ur just manipulating the deltaTime before pushin it thru
odd way of doing that imo lol
it would work but its a bit confusing
b/c deltaTime now doesnt actually mean Unity's DeltaTIme
could be throwing off code further on down the line
i'd use my ownvalue like that factored value first
but setting the heating coeffecient really low actually made it work!
and then use regular delta
so thank you
happy to help
may want to make u a debug panel to log the values real-time
on ur game..
would really help visualize whats happening as u play-test
i am going to make another line graph for each tire like this one. Right now its recording slip angle but im going to make another graph for current tempature that way I can monitor it over a period of time.
i think its Windows
LOL
its visual studio 😭
yeah im about to switch to rider over it tbh
I make code with transform with small "t" and it tells me to change to big "T" and once I do it it gives me even more errors
what was the actual error?
Show the suggestion/error
Assets\Character\CharacterMoving.cs(13,12): error CS0246: The type or namespace name 'transform' could not be found (are you missing a using directive or an assembly reference?)
the letter t in line 13 character 12
Ideally, you'd use the capitalized Transform if you're declaring a member. Lowercase if you're referring to the transform property
It tells me to change it in line 13 character 12 and once I do it it gives me even more errors
show that line of code
Show us the error line
let's not play a game of 20 questions
you need to give context
show what you're actually trying to do
not sure if the code works but it my first code I made myself to learn coding better, I will send it rn
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
//using UnityEngine;
public class CharacterMoving : MonoBehaviour
{
public float walkSpeed = 5f;
public float runSpeed = 10f;
public float jumpForce = 5f;
public float gravity = -9.81f;
private CharacterController controller;
private Vector3 velocity;
public transform groundCheck;
public float GroundDistance = 0.4f;
public Transform groundMask;
private bool isGrounded;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
controller = GetComponent<CharacterController>();
if (groundCheck == null)
{
groundCheck = transform;
}
}
// Update is called once per frame
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if (isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + Transform.forward * z;
controller.Move(move * walkSpeed * Time.deltaTime);
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
if (Input.GetButtonDown("Jump") && isGrounded)
{
if (Input.GetKey(KeyCode.LeftShift))
{
velocity.y = Mathf.Sqrt(jumpForce * -2f * gravity);
}
else
{
velocity.y = Mathf.Sqrt(jumpForce * -2f * gravity);
}
}
}
}
is my first code I made myself its janky
New bot, can't inline commands for now.
ok let me check
yeah that needs to be Transform, it's a type
Should probably include the Unity Engine namespace.
That variable field is a declaration and should be using capitalized T
you have more issues (as spawn pointed out) but you have to solve issues top to bottom
hehe.. not too bad if it is indeed ur first script tho
it gives me error still
rip dyno
u actually need this
the same error or a new one
right now its commented out
ohh well thats confusing af
Vector3 move = transform.right * x + Transform.forward * z;
lowercase t when you want to use the property
big T when declaring it as field / local var
if u wanna do ur self a disservice than sure
never use public fields...
calm down now
[SerializeField] private - one low
his first script.. lets not overwhelm him
he gotta atleast learn how references/variables work to begin with
and a configured IDE hopefully
Can I make this script on playmaker?
no one is stopping you
probably ? I don't think anyone in a coding channel uses it..
its using the same code in under the hood
I gonna try playmaker before going into text scripting
Unity has also visual scripting..
I heard playmaker more advanced
writing in c# is even more advanced
bro what
idk
he doesn't even know what a variable is, what are you even sending lol
can't you tell from random broken syntax they sent
I removed code I remaking it
you should spend the time to actually learn the basics instead of copying code
if anything breaks you won't know why, like it just happened
btw use debugging, it's great thing
Debug.Log("Player is dead"); shit like that
Transform is a type. You use it when you want to make a variable that can hold a Transform.
transform is a property on MonoBehaviour. You use it when you want to refer to the Transform component of this object.
Also make sure you know the basics of coding and oop, unity is already pretty advanced and if you dont even know basic coding then you will get overwhelmed
Learn the basics like variables, data types, loops, conditionals, stuff like that
But seeing you dont know the difference between a type and a variable i highly recommend to not go forward until you know the basics
Hello, Im trying to learn the basics of C# and Unity. Any YouTuber or online courses that you can recommend will be highly appreciated. TIA!
Note: I know I can simply do a search or ask ChatGPT for this but I'd like to know based on your experience. Something that is beginner-friendly and detailed. 🙂
check pins
Thanks! Im new to discord as well. That's helpful.
where can I learn HLSL that will work with the newest unity?
everything is outdated 😮
Unless they significantly changed how the pipeline and shaders works in the newest versions, I dont think shader language can become outdated, I had some shaders work in HDRP 2020+ versions that was written for Unity 5, with the biggest difference being a choice betweeen writing HLSL or using ShaderGraph (which is just a visual editor for HLSL with pipeline-specifics thrown in AFAIK)
But if youd like a suggestion, you can look up "Freya Holmer" she has some great in-depth videos on shader coding, or "Catlike Coding" which has a nice blog on shader coding as well - if you prefer a more visual way of making shaders, you could also look up tutorials for ShaderGraph - the former 2 suggestions do not use ShaderGraph
using System;
using UnityEngine;
public class Entity : MonoBehaviour
{
protected Animator anim;
protected Rigidbody2D rb;
[Header("Attack details")]
[SerializeField] protected float attackRadius;
[SerializeField] protected Transform attackPoint;
[SerializeField] protected LayerMask whatIsTarget;
[Header("Movement details")]
[SerializeField] protected float moveSpeed = 3.5f;
[SerializeField] private float jumpForce = 8;
protected int facingDir = 1;
private float xInput;
private bool facingRight = true;
protected bool canMove = true;
private bool canJump = true;
[Header("Collision details")]
[SerializeField] private float groundCheckDistance;
[SerializeField] private LayerMask whatIsGround;
private bool isGrounded;
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
anim = GetComponentInChildren<Animator>();
}
protected virtual void Update()
{
HandleCollision();
HandleInput();
HandleMovement();
HandleAnimations();
HandleFlip();
}
public void DamageTargets()
{
Collider2D[] enemyColliders = Physics2D.OverlapCircleAll(attackPoint.position, attackRadius, whatIsTarget);
foreach (Collider2D enemy in enemyColliders)
{
Entity entityTarget = enemy.GetComponent<Entity>();
entityTarget.TakeDamage();
}
}
private void TakeDamage()
{
throw new NotImplementedException();
}
public void EnableMovementAndJump(bool enable)
{
canJump = enable;
canMove = enable;
}
protected void HandleAnimations()
{
anim.SetFloat("xVelocity", rb.linearVelocity.x);
anim.SetFloat("yVelocity", rb.linearVelocity.y);
anim.SetBool("isGrounded", isGrounded);
}
private void HandleInput()
{
xInput = Input.GetAxisRaw("Horizontal");
if (Input.GetKeyDown(KeyCode.Space))
{
TryToJump();
}
if (Input.GetKeyDown(KeyCode.Mouse0))
{
HandleAttack();
}
}
protected virtual void HandleAttack()
{
if (isGrounded)
anim.SetTrigger("attack");
}
private void TryToJump()
{
if (isGrounded && canJump)
rb.linearVelocity = new Vector2(rb.linearVelocity.x, jumpForce);
}
protected virtual void HandleMovement()
{
if (canMove)
rb.linearVelocity = new Vector2(xInput * moveSpeed, rb.linearVelocity.y);
else
rb.linearVelocity = new Vector2(0, rb.linearVelocity.y);
}
protected virtual void HandleCollision()
{
isGrounded = Physics2D.Raycast(transform.position, Vector2.down, groundCheckDistance, whatIsGround);
}
protected void HandleFlip()
{
if (rb.linearVelocity.x > 0 && facingRight == false)
Flip();
else if (rb.linearVelocity.x < 0 && facingRight == true)
Flip();
}
private void Flip()
{
transform.Rotate(0, 180, 0);
facingRight = !facingRight;
facingDir = facingDir * -1;
}
private void OnDrawGizmos()
{
Gizmos.DrawLine(transform.position, transform.position + new Vector3(0, -groundCheckDistance));
Gizmos.DrawWireSphere(attackPoint.position, attackRadius);
}
}