#💻┃code-beginner
1 messages · Page 728 of 1
those are the same thing.
No, it is not
yes, you did
Oh, right
it's using this definition of CharacterController instead of unity's definition
oh yeah you used the same name as the unity character controller
change the name of your's or use the fully qualified name for the unity one
private UnityEngine.CharacterController _controller;
would also need to change the get component line as well
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Rigidbody2D.SetRotation.html according to this, you can pass either float angles or quaternions to SetRotation, while rotation itself is just a float
that's smart, I'll try that thanks
It's literally in your screenshot tf you mean "no"
Can you post the constructor from one of the effects, like Burn? There's another idea you can use . . .
the constructor is CS public BurnEffect(DamageController damageController = null, int effectPower = 1, float effectDuration = 1, int effectFrequency = 1) { this.damageController = damageController; this.effectPower = effectPower; EffectDuration = effectDuration; this.effectFrequency = effectFrequency; }
dude i'm asking about the behaviour lmao
When I instantiate an object, it's instantiates a clone of the gameobject. Is it possible to instantiate it so that it's an "original" version of the gameobject?
what does that mean
var clone = Instantiate(original);
the original goes in the parameters
the thing you get is a clone
sounds x y problem
the point of instantiate is making a clone of a object or creating a scene object from prefab
This is my code "Instantiate(weaponPickUpPrefabs[SelectedPrefab], transform.position + transform.forward, Quaternion.identity);", and you can see in the screenshot that the gameobject has Clone in parenthesis. I think the fact that it's a clone is messing up my script logic
Was wondering if there is a way around it before changing my script
Oh, you want to rename the instantiated object so it doesn't have (Clone) in the name
Sounds like your code is depending on the GameObject name
which is a bad idea
your logic should be written in a way the name does not matter
No, it's not depending on the name
so where and why is the name of it being used
Maybe I've misunderstood what is happening
then the (Clone) thing is irrelevant
so you should explain what's actually happening
the (Clone) part is just its name being changed
You just said it was messing up things 😐
Is the issue that some component is not "notified" of the new object or similar?
There's no difference between an instantiated clone and the original saved asset, other than the original being an asset and not an object in the scene
Unless you're trying to modify some instance data on the clones and expecting it to propagate to the original, which won't happen and is a bad way of going about it anyways
Should just really share the code, explain what it's supposed to do , and explain what's happening instead.
So I've realized I need the instantiated gameobject to have a reference to a prefab when it's instantiated
i still think you are approaching something wrong
normally the prefab is just a template and just used for instantianteing
then you keep the returned reference from instantiate to do stuff with the new instance
You want the instantiated one to refer back to the original it was instantiated from? If so, then yeah, it won't work the direct way
You can instead store the reference on a scriptable object. Its indirect, but avoids the issue you're running into
Yo
I'm having a bit of a weird problem... I'm running the game, but apparently the camera doesn't cover to screen size I set in the Project Settings
Which's 800x600
running it where?
Did you make a build, or you're running it in the editor? Or what?
I already figured there's this thing called size on the ortographic view mode, but I can't figure out how it works
Editor, mb
Editor resolution is based on whatever you set in the game window
the Game window has a resolution picker
by default it's just whatever size the window is
Ok
So, now I need to figure out why my 64x64 sprite exits the screen when I set its X position to 800
My camera settings are probably not the way they are intended to be ig
I still don't know how it works
orthographic size is half of the vertical viewing height
so with size of 400 you will see 800 total units vertically
and the horizontal size will be based on your aspect ratio
so if you have a 2:1 aspect ratio - your horizontal size here is 1600 units
So the other questions are:
- what is the position of the camera
- what are the Z and Y positions you set the sprite object to? THose matter as well.
The camera is all zero and the object is also all zero
that's wrong
the camera should be at z = -10
Now you should see the object.
If you can't, share screenshots of everything
positions of everything, inspectors, etc
Read for a while about using a struct and this is probably obvious but need a nudge in the right direction. A little confused. I know the code works for instantiate other than this part.
Forgot this part int randomSpawn = Random.Range(0, spawnList.Length);
unity uses a 3d world, even for "2d" projects
cameras only render what's in front of them, and "front" depends on the z axis
unity is a 3d engine with a lot of 2d tooling, so much so that it works as a 2d engine as well
what's your question?
a struct of just 1 member isn't.. super useful tbh. do you plan to expand this at all?
Yea. The instantiate doesn't work with that line in there spawnList[randomSpawn].gameObject so I've screwed up somewhere.
Makes sense
Well
Thank you
Done as many checks as I can but don't see where the problem is
-# geez, I can finally go study now
What's the reason behind making a struct Spawnable instead of just having an array of GameObjects?
From what I read it was better for later if extended
And what does "doesn't work" mean
No spawning or error
Are you sure that line is running
Bye
Yeap, works if I replace that part and manually tell it which gameobject
Sorry, I was AFK. There is another option with SOs. Instead of using an enum, you use a ScriptableObject enum (basically, an SO that acts as an enum). This helps because the SO will have its own method to create the effect, thus removing the switch altogether. Here's a short example
[CreateAssetMenu(fileName = "NewEffect", menuName = "hb/Effect", order = 1)]
public abstract class SO_Effect : ScriptableObject
{
public abstract Effect Create(EffectContext context);
}
Then you create derived types for each effect, like public class SO_BurnEffect : SO_Effect that override the Create method.
Before, I mentioned creating a struct or class that holds all of the passed effect data. I'd still make that; it holds all the information for an effect
[Serializable]
public class EffectContext
{
public int Power;
public float Duration;
public int Frequency;
public CharacterController2D CharacterController;
public DamageController DamageController;
public WeaponController WeaponController;
}
This is the class I used for Effect since you pass all these fields in the method
[Serializable]
public class Effect
{
public int Power;
public float Duration;
public int Frequency;
}
Now, in the EffectController, you can do this within the method . . .
public Effect ApplyEffect(SO_Effect effectConfig, EffectContext context)
{
var effect = effectConfig.Create(context);
activeEffects.Add(effect);
OnEffectApplied?.Invoke(effect);
return effect;
}
The main difference, is you pass the SO instead of an enum . . .
Try logging the object before you call instantiate
Should this actually print anything in the log if it's correct? Debug.Log("Object: " + spawnList[randomSpawn].gameObject);
If nothing prints from that log then that line is never running
If it's logging the value Object: then it means that the object in that slot is null
Hello, I don't know if I'll find the help I need here, but I'll give it a try.
I'm modding the game 7DTD and trying to create a mod that equips a helmet armor modifier. (They're like upgrades.)
Is there any way to hide the mesh/model in C# using Unity references?
we don't provide modding support here, sorry
if only the question was asked more generally, then we can point out you can disable the renderer component to stop something rendering (or remove it)
What if I continue speaking in general terms? xD
There will probably come a point where you'll get an answer that can't be implemented because of the restrictions you're working under, and that's the point support will likely end since it's highly unlikely anyone here knows of the specific limitations of this framework
Hello, Im working on a function that scrolls to a position in my scrollview based on a given index 1-29, it was working ok where the height of my UI elements was 200, then I added a title so added an extra 400px of padding to my scroll view content now it is always displaying -400px from the desired Y position and I cant for the life of me figure out how to account for the padding without messing up the maths any help is greatly appreciated!
public void ScrollToLevel(int levelIndex)
{
levelIndex = Mathf.Clamp(levelIndex, 0, totalLevels - 1);
float targetY = (levelIndex * levelHeight) + (levelHeight * 0.5f);
float centeredY = targetY - (viewportHeight * 0.5f);
float scrollableHeight = content.rect.height - viewportHeight;
float normalizedY = Mathf.Clamp01(centeredY / scrollableHeight);
scrollRect.DONormalizedPos(new Vector2(0, normalizedY), 0.3f)
.SetEase(Ease.OutCubic);
}
Is the correct channel to ask for help with a Unity Learn lesson?
what has padding, some layout group for these elements in the scroll view content?
So im just calling it padding I essentially increased the height of my scrollview content an extra 400px
sure
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #🌱┃start-here
well if you know how many elements you have and their height, you can do float ratio = (elements * elementHeight) / contentHeight;. You can then reduce the normalised scroll pos by * ratio.
Assuming that I have done this right it has reduced the gap but Is not accurate either and seemingly no longer centred on any single element
float ratio = (29 * 200) / content.rect.height;
float normalizedY = Mathf.Clamp01(centeredY / scrollableHeight);
float correctedY = normalizedY * ratio;
scrollRect.DONormalizedPos(new Vector2(0, correctedY), 0.3f)
.SetEase(Ease.OutCubic);
The point of that was to reduce the "valid scroll area" from 0-1 to the area where there is content
How can I make it so the gauge cluster lights up like on a real car?
Sorry im not sure I quite follow what you mean by this
Hey, I'm probably missing something but why are my colliders not touching?
The physics works fine, the player stops and all but is floating just above the ground.
just manually edit them see the little square? you can drag that to increase the size
I know that if my content height is 6200 and 400 of that is padding then my "valid scroll area" is 5800 but if I try and adjust the scrollable height variable by accounting for that things go sideways quick
float paddingAdjusted = content.rect.height - 400f;
float scrollableHeight = paddingAdjusted - viewportHeight;
float normalizedY = Mathf.Clamp01(centeredY / scrollableHeight);
scrollRect.DONormalizedPos(new Vector2(0, normalizedY), 0.3f)
.SetEase(Ease.OutCubic);
@languid pagoda I'm editing them but in my head the colliders should touch no?
yes click and drag and make them touch
on the collider component there is an edit collider button is there not?
@languid pagoda there is but the collider would be smaller than the sprite
I'm just wondering why the colliders are not touching, I can fix it easily but just wondering why
use emissive materials + bloom in ur post processing
@languid pagoda No problem, just tell me what you wan't to see, I'm just using a normal RigidBody2D, haven't configured anything in the project settings.
this is probably not the right channel either, tell me off if you guys want me to move somewhere else
hmm the car seats and sash use the same material idk if this will be an option but ill try. Does universal render pipeline not have an emissive material?
Oh right. The scroll view position is not for the whole content height so we also need to account for this.
Half of the viewport height/width is the area at the start and end that we cannot "center"
So technically the area we can focus on is -viewport height/width
And elements in those un centerable zones will use 0 or 1.
create another material just the needles
wait nvm the car came with an emmision texture
go into blender and add a new material / assign it to those faces
what is the name of the shader to use for this tho?
Here is my problem, why are the colliders not touching?
my unity installing 30 min, is it a bug or something?
Sounds correct yes
Does universal render pipeline not have an emissive material?
not a default material, no
they're basically prettty simple.. just a while material w/ Lit shader
seems to be some kind of offset 🤔
I'm currently trying to make my own editor window but for some reason I don't have the "tools" option on my editor. I'm using 6.2 and the image is from someone using 6.0
This is from a tutorial:
#↕️┃editor-extensions
& show any related code
oh wow this was super easy lol i just had to chuck the texture in the emissions and then adjust the intensity
obviously thats up wayy to bright but im shocked how easy that was
The Tools menu is one you'd need to create yourself. It's not there by default.
It's from a menu item, you can put any path like "Tools/My thing"
Most people use tools
thanks, I will try that tomorrow
Sure, it's a quick example. If I'm around tomorrow, I can help test it out . . .
Quick question...when running a singleton via a public class extending Monobehaviour. Is it standard practice to call it "Instance" or "instance"?(capitalized or not)
public static ExampleClass instance;
based on what I've learnt it seems like variables are normally lowercase but I've looked a bunch of examples and it seems many people do it with capitals.
style stuff is up to preference, and the style used in unity stuff differs from other C# so you will often see a mix
I assume its more about being consistent in the project?
yup
did you write code to make him fall
how do i build an MPM solver?
https://en.wikipedia.org/wiki/Material_point_method
The material point method (MPM) is a numerical technique used to simulate the behavior of solids, liquids, gases, and any other continuum material. Especially, it is a robust spatial discretization method for simulating multi-phase (solid-fluid-gas) interactions. In the MPM, a continuum body is described by a number of small Lagrangian elements ...
the algorithm is described in the article
no its not
its generalized beyond recognition in the article
https://github.com/nialltl/incremental_mpm look at this I suppose
common fix is usually putting nofriction material on the player collider
that doesnt implement anything normal fluids mechanics cant and its a failure at MPM
you could use it as a starting point for your own implementation
how did Claybook do it
how would i uhh do that
nevermind i figured out something
how do i reference the animation the StateMachineBehaviour script is on? nvm just realized it inherits from SOs
You get the Animator and the State as parameters to all of the functions on StateMachineBehavior, so you shouldn't need to
https://docs.unity3d.com/6000.2/Documentation/ScriptReference/StateMachineBehaviour.html
Trying to run a Coroutine from a non-MonoBehaviour, getting a reference to any MonoBehaviour by passing it in the Constructor or using Singleton, or is there a better solution? I want X to happen 3 times every 0.1 seconds.
it needs a object to run on, so yeah you will need to pass that along
Singleton manager that executes the routines I've done before and it works pretty well
Can anyone help figure why this is giving me a compiler issue?
Can't put functions outside the class
does c# not support free functions?
Alright someone telling why I am being dumb 😝 The error is object reference not set to an instance of an object. My brain hurts.
that but can be nice to use a related object to what it does, that way if that thing gets destroyed the coroutine also stops
C# is object oriented. Methods belong to a type.
Then one of the objects you're accessing is null (not assigned).
what line
lifehandler or spriterenderer are null
There are global scope methods in later C# versions, but unity doesn't support these versions yet.
ah, I see
Thank you
The first one switch(etc)
@random lodge you likly forget to assign something in the inspector
then lifeHandler is null. It's the only object you access on that line.
Then something on that line, probably before a . is null
Which version added those? 🤔
Alright I'll check that again
9.0 or 10.0? I dunno, finding the blog
They are called top level statements I guess. Didn't remember the proper name.
That's not quite the same thing though because those are still local functions since they get compiled into the Main method
the global scope methods are all just sugar, the cil is more or less the same as methods in a static class
Yeah, looking it at it again, it's not exactly the same.
namespace methods would be nice
not that making a utility class inside one is that big of a problem
It does seem like they're accessible from anywhere though. According to the docs.
But I imagine it would not be possible to support in unity.
can sort of do that with a static using if i we are thinking the smae thing
what would the best channel be to get some help figuring out why my UI toolkit inspector is read only?
for reference this is what I mean
I'm trying to modify scriptable objects from my custom window
Ok. How do i use the old Input system while also using the new one? I plan to use the new one for general controls and such, but fur a debug hud, I just want to simply press F1 to toggle it. Do i really have to use the new Input System package for it?
Project Settings -> Player -> Other Settings -> Active Input Handling
set that to both
I'd like to know why the heck nothing is getting printed:
The second image is how it is on both objects
The three commandments of OnTriggerEnter2D:
- Thou shalt have a 2D Collider on both objects
- Thou shalt tick
isTriggeron at least one of them - Thou shalt be moving a
Rigidbody2Don at least one of them
Check, Check, Check
Show the full inspectors of both objects
The full inspector of both objects would let me check everything at once
Just screenshot it easily
It won't fit the whole screen :/
You can hide large blocks of un-editable data like the rigidbody info
Which script has the OnTriggerEnter2D?
PlayerCollider
On player
public class PlayerCollider : MonoBehaviour
{
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D collision)
{
Debug.Log("Test");
}
}
And how are you moving the player?
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
public class Player : MonoBehaviour
{
public InputAction playerControls;
public Rigidbody2D rb;
public float MoveSpeed = 640.0f;
public Vector2 MoveDirection = Vector2.zero;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
transform.position = new Vector2(0, -225);
}
// Update is called once per frame
void Update()
{
MoveDirection = playerControls.ReadValue<Vector2>();
}
private void FixedUpdate()
{
rb.linearVelocity = new Vector2(MoveDirection.x * MoveSpeed, 0);
}
private void OnEnable()
{
playerControls.Enable();
}
private void OnDisable()
{
playerControls.Disable();
}
}
```
It's a Kinematic rigidbody setting velocity on it does nothing
wdym?
rb2d is weird man it still has velocity w kinematic
So it does, but double-checking that made me find the actual problem.
ohh nice
So, what's the fix?
-# WHY CAN'T I TYPE SO?
dynamic means its affected by external forces unlike kinematic
So... -# pls don't delete
I set one of them to Dynamic
Set the gravity to 0 just so it isn't affected by, yk, gravity
But it still prints nothing
because its unecessary noise
https://pastebin.com/yAaybB58
Any reason as to why my enemies stop spawning after like 5 spawn? something around that. I made sure to check if game state is being sate to over but its not its always playing.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Can you send a screenshot of your full unity window, with the two objects overlapping, with the console visible
You appear to have a log that is hidden
im not quite sure on the usage of [SerializeReference], i read it allow drag drop subclasses? but i dont seeing this with my script? whats the usage for this
using System;
using UnityEngine;
public class Enemy : MonoBehaviour
{
[SerializeReference]
private EnemyBehavior behavior;
[ContextMenu("Perform Attack")]
public void PerformAttack()
{
behavior?.Execute(gameObject);
}
}
[Serializable]
public abstract class EnemyBehavior
{
public abstract void Execute(GameObject enemy);
}
[Serializable]
public class MeleeAttack : EnemyBehavior
{
public float damage = 10f;
public override void Execute(GameObject enemy)
{
Debug.Log($"Melee attack deals {damage} damage!");
}
}
[Serializable]
public class RangedAttack : EnemyBehavior
{
public float projectileSpeed = 5f;
public override void Execute(GameObject enemy)
{
Debug.Log($"Ranged attack shoots at speed {projectileSpeed}!");
}
}
It does. You toggled it off.
Pretty sure it too tbh
with serialize reference you have to handle the creation and drawing logic yourself
since otherwise it does not know how to create a instance of each of the possible types or really your intent
im required to do second half to use attribute? or whats its originally use for ?
i think i maybe see it, i can pre populate the reference with code and it show up on the inspector
anyone able to help?
Wait, how does that work? The { } around the variable. You need the $ or that always works? Looks better.
congrats you just discovered string interpolation
Hello everyone, I am making a strategy game and I will be making region sprites you can conquer
But I want to make a border around each of them that changes color depending on what faction owns it
Like this for example, how could I make a border around this and be able to change its color through script
Is it something I have to do with photoshop itself or is there a tool which makes borders in Unity
Sorry if this is not the right channel to post this question, didn't really know where it could go
Wonder if there's a "stroke" option in Unity like in Photoshop.
No idea how you would if you can though.
You need to create a custom sprite shader. It's a common need and there are sprite shader assets on the store that you can get.
Alternatively you make the outline a separate sprite that you layer with the main one, and change the colour of it in code.
Chat gpt actually seems to work surprisingly well. At least way better than whatever unity uses in their Ai tools.
I am unfamiliar with sprite shaders, how do they work?
Not entirely sure what kind of answer you expect. They render the texture/sprite to the screen, basically like any other shader.
Also, #1390346776804069396
Thank you everyone, I will look more into this
public Animation myAnimation;
void Start()
{
myAnimation = gameObject.GetComponent<Animation>();
}
void Update()
{
if(myAnimation.isPlaying)
{
Debug.Log("true");
}
}
is there a way to do this but using the animator instead?
yea just realized I was looking at the animation trying to find info on animators
You can use this: https://github.com/mackysoft/Unity-SerializeReferenceExtensions (free) or Odin Inspector (paid)
is there a way to suppress certain editor warnings?
I don't believe #pragma disable works with this since there is no warning code (CS####)
how about you fix the underlying issue? 😄
And that is not a compiler issue, as such you cannot suppress them with compiler directives 😄
inverting box colliders doesn't actually cause any problems, though
I have a ton of prefabs with multiple box colliders in them, technically I am being a bit lazy by just flipping them instead of making new prefabs but that would take hours
no, 3d
Ok 
(Repost as previous wasn't so clear) (TLDR: Mesh Stretches when being rotated on any axes)
So basically when using soft-body on a non-cubical object, the mesh vertices (appear to) try and always face the same direction when rotating it using Unity's transform rotation or the node grabber. My suspicion is either: The DQS implementation is wrong, something with XPBD calculation itself or The fact that the soft-body's transform doesn't update to show positions or rotation changes. I will literally be so thankful if you (somehow) manage to find a fix for this stubborn issue!
What I've Tried:
-Rewriting the scripts
-Renaming all variables properly
-Used different Mapping methods
-Debugging
-Using the Help of AI
Video: https://drive.google.com/file/d/1bYL7JE0pAfpqv22NMV_LUYRMb6ZSW8Sx/view?usp=drive_link
Repo: https://github.com/Saviourcoder/DynamicEngine3D
Car model and asset files: https://drive.google.com/drive/folders/17g5UXHD4BRJEpR-XJGDc6Bypc91RYfKC?usp=sharing
wait is this the correct place to post this?
Post either here or code-general but not both
I'm having issue, whenever I save my script , it takes time in compiling and all, any way to lessen up the time
It needs to compile when you change something in a script. of course, you can turn the behaviour to only compile when entering playmode for example, but in that case, you will not see updates on your script you want to see in edit mode for example. Maybe try to think through changes first and do not change/save every line or whatever your frequence is in changing and testing.
You can also disable auto refresh in editor preferences to prevent it from auto detecting file changes. Would need to run it manually though to apply changes.
I did this too, just gotta hit ctrl+r to refresh manually
much better than having to wait for the refresh every time I tab away and back to double check something
private void Update()
{
// check for sight and attack range
playerInSightRange = Physics.CheckSphere(transform.position, sightRange, whatIsPlayer);
playerInAttackRange = Physics.CheckSphere(transform.position, attackRange, whatIsPlayer);
if (!playerInSightRange && !playerInAttackRange)
{
Patroling();
animator.SetBool("isWalking", true);
animator.SetBool("isRunning", false);
animator.SetBool("isShooting", false);
}
if (playerInSightRange && !playerInAttackRange)
{
ChasePlayer();
animator.SetBool("isWalking", false);
animator.SetBool("isRunning", true);
animator.SetBool("isShooting", false);
}
if (playerInSightRange && playerInAttackRange)
{
AttackPlayer();
animator.SetBool("isWalking", false);
animator.SetBool("isRunning", false);
animator.SetBool("isShooting", true);
}
}
This is not a clean state machine. It's possible for your code to enter more than one of these in a single frame
Look up the state machine pattern. At the very least use else ifs.
problem is almost definitely inside your Patroling() function. my guess is you set a destination once and the bot just stops when it gets there. inside Patroling(), you need to check if the agent is close to its current destination (using something like agent.remainingDistance < 0.5f) and if you're not sure which state is active put a Debug.Log("Patrolling") in that first if statement to see if it's even being called
you think I should use else ifs and elses? instead of ifs?
I wouldn't have written it if I didn't think it
If i need make a ui text as integer or real number to increase it with variable should i make it in code or in unity?
private void Patroling()
{
if (!walkPointSet) SearchWalkPoint();
if (walkPointSet)
agent.SetDestination(walkPoint);
Vector3 distanceToWalkPoint = transform.position - walkPoint;
// walkpoint reached
if (distanceToWalkPoint.magnitude < 1f)
walkPointSet = false;
}
private void SearchWalkPoint()
{
// calculate random point in range
float randomZ = UnityEngine.Random.Range(-walkPointRange, walkPointRange);
float randomX = UnityEngine.Random.Range(-walkPointRange, walkPointRange);
walkPoint = new Vector3(transform.position.x + randomX, transform.position.y, transform.position.z + randomZ);
if (Physics.Raycast(walkPoint, -transform.up, 2f, whatIsGround))
walkPointSet = true;
}
Should you make what part in code or unity? The UI text object itself?
yea sorry, I just didn't understand exactly what u meant by that, my english isn't really good
it's always setting the bool false when the bot is near it
Yes need make it as Variable value and make the var +1
which should then find another one
That wasn't a yes or no question
Which part?
Sorry?
It is going to require both code and objects designed in the editor
There are code parts and editor parts. You need both
sent you
Yes so should i change something in text to something?
Couse now its just text
That might be the most vague question I've ever seen.
Should i make it number or it will be in code directly?
I'm honestly not really sure what question you're asking
You will need a numerical variable in your code and a reference to the UI text object. The code will update the variable and then update the UI with the new value as needed.
@lavish rose there is no issue right?
Now I have added some text, do I need to change something about it so that it is treated as a number so that if I visit the number variable it will increase with it or will it just be part of the code?
The number variable should be separate from the UI element reference
Like if i make int var and make the Text in it then +1 to this var
Text will be 1 to 2 maybe?
What do you mean by "make the text in it"?
In code like variable tmp
Pseudocode:
myNumber += 1;
myText.text = $"Health: {myNumber}";```
Huh
if it were a string u would convert to int to add
string numberString = "42"; // number as text
int number = int.Parse(numberString);```
but u wouldnt want to use strings there
String parsing is definitely not the way here
And add ui text tag in it or?
I don't understand what you mean. Tags are not related to this
its the TextMeshPro's text field
private void UpdateHealthUI()
{
healthText.text = currentHealth.ToString();
healthText.text = $"{currentHealth}";
}```
both would output `currentHealth` as text
string interpolation, one of the best invention ever
i agree
I mean tag for this 0 to link it with variable
you don't link it with a variable. When the variable changes you need to update the text with myTextField.text = someVariable;
ugui cannot do this
UI toolkit has this functionality though
Some variable its mean do var right?
I know if i ask you will told me to search
i'd usually use a UIManager that already has the references to all the text elements i need
tell it to Update it (when it changes)... uiManager.UpdateSoAndSoText();
alot easier to find something like that (or even use a singleton) than it is to grab every element individually.. if i need to scoop it at runtime
that way u dont even need a Tag to get it
UI toolkit may be too advanced to use but you can read more here: https://docs.unity3d.com/6000.2/Documentation/Manual/UIE-data-binding.html
I still don't know how i will tell it to know which text i need to change
you assign that in another script.. already
like i just said.. something would alrady be referencing all the TMP elements that u need
I do it with same coins script like destroy coins and +1 for text
So add Same script in both of them?
both scripts could call the same script
that way u could tell the UI Manager (the brains of the UI) which could hold all ur UI stuff
and the UIManager does the updating (with the text reference it already has) b/c u would assign that in the inspector
Ok but how it will know which text im want
Yes ok
public class UIManager : MonoBehaviour
{
public TextMeshProUGUI coinsText;
public TextMeshProUGUI healthText;
private int coins;
private int health;
// Called by other scripts
public void SetCoins(int amount)
{
coins = amount;
coinsText.text = $"Coins: {coins}";
}
public void SetHealth(int amount)
{
health = amount;
healthText.text = $"HP: {health}";
}
}```
think of it like that ^
Then should i call text which i want to new var
hey, i have all the references i need to change anything in the ui
i'll just wait for someone to call one of my methods
uiManager.SetCoins(newCoinAmount);
uiManager.SetHealth(newHealthAmount);```
that way ^ u only need to get (1) script for any UI changes u need to do
u dont want to be having to "search" and then assign all ur Text elements at runtime
its not very scaleable..
So I don't feel like my mind is frozen
Now lets say my text in unity is scoretext
And i make var with score text for it
Then make other int to make it +1
Right?
Thats what i know to make code know which text i need
you do whatever u need to do to calculate the score..
then you use .text of the textmesh element to change the text
you can use anything u want (but for this case you'd use ur score variable u calculated)
1 variable for the score
1 variable for the text
Ok how text will know which text i mean 🙂
Add same tag or something?
Like var score = "score tag"
bro.. you'd just drag and drop the fkn text element into a variable
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
no.. if anything you'd get the reference first
You really should go through unity basics from what I assume reading your questions
valid crashout
How should i drag it?
u can really just assign it
Yes got it
assigning variables in the inspector is pre-game sht #💻┃code-beginner message
I should click yes right?🙂
click no and fix the bugs then make the TextMeshPro public so you can assign it in the editor.
ok so.. ya a few things here
- https://www.take-a-screenshot.org/
- #💻┃code-beginner message
startis notStart()(so that code isn't gonna work anyway)
there is never a reason to build a unity game in your IDE
Why are you even trying to run it in your IDE
Will it change in unity automatically?
Just click attach to unity
the editor recompiles when it sees changes
Are you trying to use the debugger?
Please, I beg you go through the beginner tutorials on Unity learn
without taking some time to understand the basics you are going to have a bad time and waste much more time in the long run
Whatever see both If there are any errors that do not exist, they will appear when running it from the editor as well.
And no errors now
You should be seeing compile errors highlighted in real time as you make them without attempting to attach a debugger
No space added for the new variable.
Just nrp
Do you have any compile errors
No
How about showing a screenshot (not a cell phone picture) of your unity console
In unity yes but i think its not from code syntax just null from loop
When i run game
it needs to be public to show up in the inspector
Ok its appeared now
👏 gottem!
I cant find text when i click in it🙂
drag in your text object
And cant drag it because its selected when i click on it
Click on object with variable.
Drag in text object
You don't need to select the text object
Why can't i send screenshot from pc🙂
you can..
people are gonna stop helping or moderation will step in if u keep sending blurry photos
but you now need to fix that MissingReferenceException
Oh wait
read the error..
2004 camera vibes
I understand him wrong
how do you expect people to help if you cant share things CLEARLY
my amazon fire from 2018 takes better pictures
Phone camera so
why not?
bro you've literally been told 2 days ago to learn to screenshot normally
why do you go back to using camera
Will back to it
try click on the circle thing
😄
Empty
what
Yes
click on this and show me inspector
and then show me the code
no, unity is not buggy, something is just wrong..
I am done even reading this chat 😄 You seem to be fully aware to ignore the fact, that you are missing the most basic concepts of Unity entirely. People will waste their time helping you fighting through the most simple tasks and you wont learn anything...
Here its
They helping so🙂
if it doesn't allow u drag it into the slot then that means the Type of component ur trying to assign isn't on that gameobject
Aaa can't do that i don't know why
Tmp ?
learn the basics your are just wasting your time and others
ur ignore ppl w/ valuable information
Just changed it to public
i download this demo but it say no camera what i should do to fix?
you know Save next?
then tab over to unity , (give it time to recompile)
and if its successful u should have a variable in the scripts/ component
theres probably not a camera needed in the Menu scene that ur lookin at
or its spawned in later or with a scene change
u can disable the warning by right clicking the Game tab
or add a camera if u want ¯_(ツ)_/¯
full screen if he need it
Thank the Lord! 🙏 finally not a phone selfie

show the inspector of the GameObject ur trying to drag into that slot
Failed
and when you get around to it you should click/dblclick this error and see where its coming from
But its above
b/c it is something you have to fix eventually
no.. its not above..
thats not a picture of the inspector
There are almost no real errors. It's just an error in the loop. I think he doesn't find anything to redo when the ball dies. Now I just want to solve the variable problem.
Rrrrrrr
but after that code runs the script breaks.. nothing else will run
Here its
3 scripts?
the one w/ the reference ur trying to drag in
the one u cant drag into
lol.. funny
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UI;
public class get_coin : MonoBehaviour
{
public Rigidbody2D nrb;
public TextMeshPro score;
private int scoreValue = 0;
void start () {
}
void Update()
{
nrb.velocity = Vector2.up * 300 * Time.deltaTime;
}
void OnTriggetExit2D(Collider2D other)
{
if (gameObject.transform.position.y > 7)
if(other.gameObject.tag == "player")
{
Destroy(gameObject);
scoreValue += 0;
score.text = score.ToString();
}
}
}
ah
well holy crap
^ either that or TextMeshPro_GUI some nonsense
its not a shortname?
no, its TMP_Text, he needs text
no
Wait
also holy pls format your code or smth 😭
In unity i was added tmp
its messed up bro
I hate that failed
bro, just change TextMeshPro to TMP_Text
whats so hard about that
nothing failed, you just made a typo with the variable type
TMP_Text is the base class for TextMeshProUGUI and TextMeshPro. It's better to use TMP_Text but the UGUI one will work in this case aswell.
yes that will work..but public TextMeshProUGUI scoreText; also would work..
its like a Blanket variable that covers many different types of text mesh pro elements
didnt know lol
but irregardless yes
#💻┃code-beginner message
i concur
But both is tmp at the end
ignore that...
public TMP_Text scoreText;
and move along w/ ur day
has anyone else downloaded the official Spaceship demo? I’m getting errors in SelectionHistoryWindow.cs (like CS1010: Newline in constant) even after trying some fixes. Did anyone else encounter the same issues?
yeah i dont think he needs the features Ugui gives anyways since all he needs is just .text
just fix your code and thats all
this is a channel for help relating to code you've written - can you delete your questions from here and ask in #💻┃unity-talk
no idea.. in situations like that where im trying to revive an outdated repo
i'll usually go in surgically and find the errors and ``// comment them out`
i'll then re-attempt to compile/run it... and rinse and repeat and even temporarily remove / rename scripts if
the whole thing is bugging.. and then u need to go thru the solution and remove any references to that script.. b/c that would cause it error out.. (sometimes i'll comment them out as well)
ok thank u
sometimes its helpful.. sometimes its not.. usually u can get away with it running (albiet a few features might not respond)
Is the new version Is the screen control faster?
ya... i know just figured i'd affirm that it does work.. b/c may be useful to other bystanders that already been thru the learn courses 😉 being community server n all
It is not convenient every time I choose what I want from screen movement, element movement, selection, etc.
you've confused tf outta me ngl

what??
Cant do like double click for select log click for move and this thing
I must select everything first and change it to what i want
Are you asking if there is a quick way to rename something?
No wait
quick way for those
with mouse
QWERT will swap between them
What is that?
... keys on your keyboard.
idk if this is the right channel, but how ressource expensive is it when i shoot 3 raycats in an FixedUpdate() function?
and also do some rotations
raycasts are not very expensive
okayy
3 in a frame update or a fixed update is no big deal
good to know
how expensive is a transform.Rotate() since i am calling that also
but i guess no big deal either
just make things work first
only worry about performance if it shows its a real issue
if that happens you have tools like the profiler to debug why
alright good to know, thank u
but yeah a rotate is pretty cheap as well, though try to not rotate the same objects many times on the same frame.
which should be easily avoidable by just figuring out the final rotation first
well i am aiming for a continous rotation tbh
that does not require multiple rotates on the same frame though that is just 1 per frame
void FixedUpdate() {
float rotateDirection = rotateRight ? 1f : -1f;
transform.Rotate(0f, rotateDirection * rotationSpeed * Time.deltaTime, 0f);
}
this is what i did
yeah totally fine
ahh okay
fixed update is really only needed for physcis stuff
otherwise Update is the better choice
yeah can raycast fine in Update, stuff like moving a rigidbody should be fixed update
90% of other thigns are regular Update
okk that makes sense
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
thx for answering so fast
what?
not sure u can be telling ppl to use something u seem to be actively ignoring
you mean me?
No me
oh ok
Oh ok
error on the learn site?
Yes
odd, its working for me
that's not much info to go off of
you're gonna need to give more info if you want help
Why cant i see the camera?😂
Did you remember to open your eyes
Ummm no there is no camera
Well if there isn't one that's a good explanation for why you cannot see it
Ok its back

Box collider should make rigid body stand in it right?
what do you mean by "stop in"?
Like Stand on it or something
you can chain boolean and assignment right?
A = B = <boolean>```
You can chain any assignment as long as you don't have more than one constant
public void UpdateStatus(bool isActive)
{
col.enabled = isActive && isActivated;
renderer.enabled = isActive && isActivated;
col.enabled = renderer.enabled = isActive && isActivated;
}```
the assignment operator returns the value that was assigned so yes
ok ty 👍
bool x = a & b; is no different from bool x = a = b; grammatically.
good to hear i can finish it within one line lol
I meanI would probably just make a property
bool _active;
bool active {
get => _active;
set {
_active = col.enabled = renderer.enabled = value;
}
}```
hmm guess you could use the chain assignment in the property too hehe
i would need to replan the isActivated in this case
done , i removed isActivated and can now make it to property 👍
I don't know what happened but coins doesn't destroyed or text increased
Code
I think i got it
Hi!
Can someone DM me who knows ML-Agents and can help me out?
very unlikely someone will do that, we encourage you keep it on the community server... better you make a post in the appropriate channel and clearly explain your issue
#1202574086115557446
i do that but its same thing
do I need the effect class for this? If I return the effect in the Create() method, it would be a BurnEffect that derives from SO_Effect, but it will actually not let me return either because its not of type Effect
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEditor.EventSystems;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class get_coin : MonoBehaviour
{
public Rigidbody2D nrb;
public TMP_Text score;
private int scoreValue = 0;
void start () {
}
void Update()
{
/* nrb.velocity = Vector2.up * 300 * Time.deltaTime;
*/
}
void OnTriggetExit2D(Collider2D other)
{
if (gameObject.transform.position.y > 7)
{
Destroy(gameObject);
}
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "coin")
{
Debug.Log("Coin collected! "+ scoreValue);
scoreValue += 1;
score.text = scoreValue.ToString();
Destroy(gameObject);
}
}
}
you misspelled trigger
so what should i change
spell Trigger correctly...
where?
why don;t you look at your code until you see where it's not spelled correctly. There's not that much.
Consider the fact you've used the word Trigger twice in that code, you should be able to spot it.
Furthermore, your !ide should be configured, it would be underlining it red.
!ide
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
• :question: Other/None
well in this case it wouldn't underline it red, no? It's not a compile error.
i see but ididnt find it
look line by line
if the ide were configured the method would be marked unused
Which of these two are not liked the other?
bro its from suggesion
any way i do enter also
and doesnt work
Niether of those sentences actually answers the question posed?
i think you didnt got my quistion
Depending on the IDE it might get underlined in gray as "unused"
Look harder
Now here i make collider as a trigger for coins and like the code if it enter triggers destroy and +1 and nothing happened of those
because you misspelled trigger
did you fix the spelling mistake you had pointed out to you several times
Also i tried change tag to player but same
Yes
Show it
Be trigger
did you save the file and refresh in unity too
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEditor.EventSystems;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class get_coin : MonoBehaviour
{
public Rigidbody2D nrb;
public TMP_Text score;
private int scoreValue = 0;
void start () {
}
void Update()
{
/* nrb.velocity = Vector2.up * 300 * Time.deltaTime;
*/
}
void OnTriggerExit2D(Collider2D other)
{
if (gameObject.transform.position.y > 7)
{
Destroy(gameObject);
}
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "coin")
{
Debug.Log("Coin collected! "+ scoreValue);
scoreValue += 1;
score.text = scoreValue.ToString();
Destroy(gameObject);
}
}
}
Yes
I will take Break for hour
good idea
The three commandments of OnTriggerEnter2D:
- Thou Shalt have a 2D Collider on both objects
- Thou Shalt tick
isTriggeron at least one of them - Thou Shalt be moving a
Rigidbody2Don at least one of them
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.
Would Vector3.Reflect be the right choice if I want to "bump" an asteroid off course with another object in 2D?
Possibly - it depends what behavior you want
Reflect will give you the bounce of a pool ball on the wall of the pool table, or the bounce of a ray of light off a mirror
It's possible you want some other kind of behavior. For example in "brick breaker" type games the ball bounces off the paddle at a different angle depending on which part of the paddle it hits.
also I don't think it works if the asteroid isn't moving
Yea the angle would be nice
you could also just lean on the physics engine
Currently the asteroids are moving down across the screen on their own. At the moment the ship only moves left to right. So as they move down the player would nudge them if they move left into them. I was hoping it would nudge/bump them at the angle the ship hits them from. Also want to possibly add some extra rotation from it.
Basically a Galaga type game but I'm adding a lot of deep intracies to everything's behavior
then reflect could work
well how are the asteroids moving? If they are dynamic Rigidbodies you would get that behavior for free
yeap they are, currently before I changed anything the behavior was a bit weird
They would kind of move through the ship and then go off course behind it
are you moving the ship via the physics engine? Or teleporting it around via the Transform
what components does the ship have?
In this scnario I would give the ship a kinematic Rigidbody2D and move it via Rigidbody2D.MovePosition in FixedUpdate
Like this at the moment
just like that at the moment
you'll need a better collider
use a PolygonCollider2D
gotcha
@wintry quarry long time no see! Awesome to see you still helping people here! ☺️
hey guys. Anyone ever experience a 55ms RenderLoop? & Is my Profiler looking brutal in general 🥲
can someone remind me on how you check if a raycast you sent out actually hit anything?
and more importantly how you know what it actually hit
thanks
log its RaycastHit return
the return value (true/false) tells you if anything was hit at all
The information about what was hit will be in the out RaycastHit parameter, which is optional.
i'm trying to make something like ultrakill's coins in 2d, would it be good to use FindObjectsWithTag and compare every item by proximity or is there an easier way to do this?
well how do I access the out parameter then?
or like how does this work
I don't know what ultrakill is but no. Just do an OverlapSphere/OverlapCircle (3d/2d) or use a trigger collider
bc if i do this in a room with lots of enemies in, it'll have to check the positions of every one of them until it finally finds the one closest to the object
it bounces to the nearest enemies in the room
throw a coin, shoot it, it goes to the nearest active coin or the nearest enemy if there are no coins active
yes do what I said and only check the distances of the enemies within nthe sphere/circle
alright
but you have to check the whole room and only the room
oh so it just gets stored in a temporary variable basically?
the scope of the variable is up to you but yes it's a way for the function to directly assign a variable in the caller's scope
then use the appropriate check for the room shape
if it's a box shaped room, use OverlapBox
so should i just figure out what i want the maximum range for a rebound coin to be and then check for any enemy or coin inside that radius
that would go through walls
oh shit yeah
what if i use a raycast to find whether or not the object is blocked by a wall
Yeah that's exactly what I've done before
yes. If you want to avoid going through walls you can combine that with Collider.raycast for each candidate
yes exactly
that would work yeah
or maybe CircleCast if you want it to have some "thickness"
i'll just set the maximum distance to be like 3x the camera's fov
so that way, it's far enough for you to not be missing against enemies you can see but not so far that you could snipe some poor bastard from 6 lightyears away with help from a convenient hallway
Seems you have it solved, but figured i'd drop info about it
It basically throws a coin (which has a collider obv), then when the revolver shoots it creates a beam object which handles the cast along its direction + other information, then then that beam "shoots" it checks what it hits (such as a coin which then just gets its component to run a function on it). And in that case, it's just a standard raycast with infinite distance. The coin itself handles any extra reflections off of itself when called from the beam.
but how does it find the right enemy to hit when there are multiple nearby?
or am i just being an undertale fan
Where to learn unity C# concepts. Any playlist or YouTube video
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
What do you want to learn exactly?
I'm trying to make a tpp game, but unfortunately i stopped using unity 4 yrs ago and forgottenost of the things, although I'm good at modelling and all in blender. But now I want to know main concepts regarding tpp in unity
But only c# part
Raycast stops on the first hit, so the beam is just the first. Then the reflection from the coin first checks all the coins in the coin list, then all grenades in the grenade list, then it does a FindGameObjectsWithTag("Enemy") (each with their own checks)
YouTube, Unity docs, Unity Learn, websites galore, C# websites, etc 😉 The glory of modern times. I remember when you had to mostly buy a book. It sucked. lol
Nice! I only do TPP too. I hate FPP
Let me find you some videos that helped me before
oh that makes sense
what's tpp
does that not get intensive if you're in a room with like 500 filths
Third Person Perspective
oic
I know but like when I was following one tutorial it helped me learn what are the better ways to solve the Same issue, and what else is there to learn and guided by the teacher in YouTube.
I usually end up looking at 10 different sources for the same thing I want to figure out
So, I only have youtube option, I do read docs sometimes
go try it out
But only really if you have like multiple coins all doing the same reflection every frame and what not. Could probably do an enemy list instead so you didn't need the search anymore. Works for them so is probably fine to a degree.
Haha, Starlord and Galactus
i have no idea why i'm not using a coin list myself to be honest. i should add that
it'd make life a whole lot easier
Unity Helpful Videos
Movement, Physics
https://youtu.be/NsSk58un8E0 (Advanced Movement Shooter Physics In 1 Hour)
https://youtu.be/jSauntZrQro (Anatomy of an Advanced Player Controller)
https://youtu.be/dLYTwDQmjdo (Unity3D Physics - Rigidbodies, Colliders, Triggers)
https://youtu.be/YR6Q7dUz2uk (Collide And Slide - Actually Decent Character Collision)
https://youtu.be/c1PAoxY7v54 (Basic third person controller)
Development Patterns
https://youtu.be/BwA36em_DnA (3 Game Programming Patterns WE ACTUALLY NEED)
https://gameprogrammingpatterns.com/singleton.html
https://gameprogrammingpatterns.com/state.html
https://www.youtube.com/watch?v=V75hgcsCGOM (Jason Weimann in-depth on State Pattern)
why are these Debug.draw raycasts lines not actually showing anything?
like am I supposed to be seeing the raycasts or
enable gizmos
also aren't the rays only visible in scene view, not game view?
Both if you have gizmos enabled in each window
@analog pendant those videos are a great place to start. Some of the Unity YouTubers go more in-depth into advanced stuff. git-amend for sure, Jason Weimann, Game Dev Beyond the Basics, others too.
do I not already have everything enabled?
Yes enable that. And if the ray is coming from the camera along forward, you will not see it. If that's the case, you can add a duration so you can move a bit and see it.
well how do you add a duration to a raycast?
https://docs.unity3d.com/6000.2/Documentation/ScriptReference/Debug.DrawRay.html
Looks like the 4th argument.
I still don't see it despite making the float super high though?
Debug.DrawRay(transform.position, _camera.transform.TransformDirection(Vector3.forward) * 1000, Color.white, 5000);
am I doing smth wrong here?
gizmos in the corner of the game window isn't highlighted
If you want to get the camera's forward direction you can just use _camera.transform.forward
I mean like just selecting it still doesn't seem to change anything?
or am I missing smth
What calls DrawRay? Is that object actually in view?
So, it's the player object, and it's pointing out straight along the center of the camera
I think you are getting the ray, but you're looking at it straight on.
yeah?
Try pausing the game and looking in scene view
Where you can get another angle at it
ok so you're right but why can't I see them even when I move away from them?
like they're there but I can't see them when actually playing for some reason
(Also for future ref _camera.transform.TransformDirection(Vector3.forward) is just _camera.transform.forward)
gizmos are off
(pressing the gizmos button changes nothing)
MainCamera render settings culling mask?
it might be because i'm using 2d or something, i'm not sure, but it's working ok for me
there is a possibility we're on different versions but i'm not sure
Still negative
this is not very sigma
Switch from Free Aspect to 1080p? Hehe idk. It messes with OnGUI sometimes
I use DrawRay all the time. I'm in Unity 6.2
I dont need to put OntriggerEnter into update right?
where's that?
No it runs automatically.
okay thx
Above the game itself, look for Free Aspect.
not a code thing but the player does not need to be a trigger, just the collier right?
I don't see it
From ur own screenshot 😜
Have you had success with DrawRay before? I've done it in Unity 6.1 and 6.2, no issues ever
Depends what you want to achieve. Does your player have a CC component or RB?
I am trying to make a dash in my top down 2d game, I tryed probably four or five difrent methods how to implement it, followed a few tutorials...
RB
no this is the first time I'm trying it
no changes?
and it just doesnt work, the script gets executed, but the player just wont move
here is the script
if (dashA.triggered && canDash){
StartCoroutine(Dash(Vector2.left));
}
if (dashW.triggered && canDash){
StartCoroutine(Dash(Vector2.up));
}
if (dashS.triggered && canDash){
StartCoroutine(Dash(Vector2.down));
}
if (dashD.triggered && canDash){
StartCoroutine(Dash(Vector2.right));
}
in the update methot
and a Ienumerator
that seems inefficient
IEnumerator Dash(Vector2 direction) {
canDash = false;
IsDashing = true;
tr.emitting = true;
currentDashTime = dashTime; // Reset the dash timer.
startDashTime = Time.time;
rb.AddForce(direction * dashSpeed * Time.fixedDeltaTime);
yield return new WaitForSeconds(dashTime);
tr.emitting = false;
IsDashing = false;
yield return new WaitForSeconds(dashCooldow);
canDash = true;
}
what object is transform here? Is it the camera?
do you have seperate dash buttons for each direction?
How to reproduce: 1. Open the “IN-100345.zip“ project 2. Open the “Game“ Scene 3. Open the Game view 4. Enable the “Gizmos“ in the t...
What is the goal of using Trigger colliders? usually they are good for "player has entered zone" or things like that.
how does your regular movement code work?
checking if they are in an attack
A tool for sharing your source code with the world!
that doesn't answer the question
which object is this script on?
i got it working btw just had to change a few things in the attacks themselves
Yeah for sure. So like, OnTriggerEnter or something.
Jeah I do, becouse I want the to dash get triggered bz double tapping the butons
yup
aka it is broken in your version
So, either the player has to detect if it's being attacked, or the enemy has to let the player know
Both methods have their advantages and disadvantages
void Update()
{
if (IsDashing) {
AirFriction();
}
if(IsDashing == true){
return;}
//movement
movement.y = verticalAction.ReadValue<float>();
movement.x = horizontalAction.ReadValue<float>();
//trigering dash
if (dashA.triggered && canDash){
StartCoroutine(Dash(Vector2.left));
}
if (dashW.triggered && canDash){
StartCoroutine(Dash(Vector2.up));
}
if (dashS.triggered && canDash){
StartCoroutine(Dash(Vector2.down));
}
if (dashD.triggered && canDash){
StartCoroutine(Dash(Vector2.right));
}
}
//movement execution
void FixedUpdate()
{
smoothMovement = Vector2.SmoothDamp(smoothMovement, movement, ref movementhSmoothVelocity, 0.1f);
rb.MovePosition(rb.position + smoothMovement * MoveSpeed * Time.fixedDeltaTime);
}
zzzz
it is a simple movePosition
is there any alternatives to it?
why not have an array to act as an input log, and if you input the same direction twice with the only other input being neutral then you dash in that direction?
i think something like that is what fighting games do
saves you having the same line of code 3 times for each direction
your code is doing MovePosition every fixedupdate, that's going to override the force
MovePosition and MoveRotation are for Kinematic RB.
This allows Interpolation to still work.
AddForce and AddTorque are for dynamic RB.
This allows Interpolation to still work.
If you are going for non-kinematic RB, prepare to learn about PID. Springs, dampening. Integration, calculus all that
thank you
no worries
Either go down to 2022, go to 6.2 (which seems unstable from some people that are trying it), or use a lib like https://github.com/nothke/NDraw (haven't tested this myself) or something similar
ou, so I need to stop the movement while dashing
yes
if your movement system involves setting the position every frame then external forces will not apply
@rough blaze it looks like you might venture into "if statement hell" aka Code Smell "switch"
Sooner than later I recommend you try the State pattern
that's why if you want to make a more fluid movement system it tends to be best to use forces and change them to get the velocities you want, only setting velocities when it is appropriate to do so and won't override any other important movements
ok
cool so I just don't use draw rays anymore basically
raycasts themselves work fine right?
it's just that they can't be drawn on the screen yes?
Any reason you don't wanna go to Unity 6.2?
I don't rly see a reason to if it's just this one thing that's broken
Fair enough. Tbh i've been worried about frame stutter in Unity 6.2
I have 6000.1.7 and draw ray works for me
I feel like the Editor is slower. Not 100% sure but. Just a feeling
I can still get like 600 fps if I uncap framerate (-1), but still a frame gets dropped occasionally
So weird how the CPU and GPU are like <2ms, but a frame can be dropped?
⭐ hi guys, what is a good method for sharing constants between class instances?
Context
I am doing a bunch of Animator.StringToHash() on Awake
All the hashed values, need to be accessed by child instances of the parent class, StateOfMotion.cs
Hence all "sub types" need access to those same pre-hashed constants
Project-wide sharing, would I just make a static class and static variables?
Class-wide sharing, would that be static variables accessed like StateOfMotion.hash_IdleLoop1 ?
static field?
Sure, like in StateOfMotion.cs parent class?
So then the usage is like StateOfMotion.hash_RunLoop1?
yeah
Any reason I would wanna do it that way instead of a Project-wide Constants.cs static class?
depends on the specifics but either would do the job
hey im trying to make a basic top down movement script with the ability to dash in any direction to gain a bit of a boost. this is my code know and while i know it doesnt work because the velocity added by the dash instantly gets overwritten by the normal movement, i dont really know how i should fix it. heres the code i use: ```cs
private void Update()
{
Vector2 direction = Vector2.down;
if (direction != playerControls.defaultMovement.Move.ReadValue<Vector2>().normalized)
direction = playerControls.defaultMovement.Move.ReadValue<Vector2>().normalized;
if(playerControls.defaultMovement.Dash.WasPressedThisFrame() && currentDashCooldown <= 0)
{
rb.linearVelocity += direction * dashSpeed;
currentDashCooldown = dashCooldown;
print(direction*dashSpeed);
}
else
{
rb.linearVelocity = playerControls.defaultMovement.Move.ReadValue<Vector2>().normalized * movementSpeed;
}
currentDashCooldown -= Time.deltaTime;
}```
stop running the normal movement code while you're dashing
came to that conclussion too, how can i find out if im still in the dash or not?
make a variable to track it
use a timer or a coroutine to set it back to false when you're done dashing
so its time based rather velocity based?
Is the dash supposed to take a certain amount of time, or just influence the velocity a certain amount?
A hybrid system can work too where it's a bit of both.
im not really sure what makes more sense, i think its more precise if i do it time based? i dont know tho
that sounds interesting how exactly would that look like?
Maybe, how long you hold the dash button allows it to continue longer? One option
For the actual resulting movement, you can allow some influence that combines with the hard-coded "dash amount" or "dash direction"
ASAP, I would switch to using the State Pattern though.
state pattern???
It's much easier to add dashes, vaults, "hard landings" after midair, and all that
Yeah have you ever used Enums before? It's similar to that
how come as soon as i start something not very complicated i immediatly get overwhelmed haha
a little bit but i never really understood them
Like,
if (state == MotionStates.Idle) idleStuff(); else if(state == MotionStates.Running) runningStuff();
Making a custom character controller is very complicated
https://paste.mod.gg/sefzqlbploti/0
hey so like I've managed to figure out how raycasts actually work and kinda rendered them but I'm not sure how to actually check what they hit 
A tool for sharing your source code with the world!
anyone smarter than me know how to do this?
the out hit is what is hit
do I just do if (hit == GameObject.Find("objectImLookingFor"); then or smth?
using Enums for State is like the quick & dirty method. Basically an upgraded (if this, if that, if not do this, etc)
Typically a State machine works more like this
nextState = state.CheckForTransitions()
nextState = state.CheckForTransitionsPlayerControlled()
// if either above method said, time to switch to a new state
if (nextState != null)
state = nextState```
Debug.Log ( hit.transform.name ); for example
And no, you cannot GameObject.Find as a way to compare something.
i dont understand anything but ill look into it through documentation/yt tutorials thanks for the advice!
if (hit.transform.name == "object") ?

sure
You probably shouldn't tie functionality to object names and should identify them by something that can be checked at compile time
Trust me you won't be able to make a video game without learning these Game Dev patterns.
thanks a lot im watching a yt video about it rn, ill look at this right afterwards!
They literally came about as people tried to solve the issues in game making
like a tag? or?
Tag, component, something you can actually get some sort of feedback if it's incorrect
well how do you check what tag an object has?
Instantiate and destroy objects a lot? Object pooling!
200 if statements in a row? State pattern, separate the logic!
Checking 20 variables every frame that rarely change? Event pattern!!!
Share some configurable states between instances? Scriptable objects!
You can probably pop that exact question into google and include the word "unity" and see what it gives you
true
Cheers wish u luck! We're always here to point in the right direction. 💪
would smth like hit.collider.gameObject.CompareTag("tagMyObjectProbablyHas") work?
You would create two separate classes. An SO for the burn effect and a C# class for the runtime version of burn effect
[CreateAssetMenu(fileName = "Effect_Burn", menuName = "hb/Effect/Burn", order = 1)]
public class SO_BurnEffect : SO_Effect
{
public override Effect Create(EffectContext context)
{
return new BurnEffect
{
Power = context.Power,
Duration = context.Duration,
Frequency = context.Frequency,
DamageController = context.DamageController
};
}
}
[System.Serializable]
public class BurnEffect : Effect
{
public DamageController DamageController;
}
This is an example, so it's barebones. You'd add other necessary fields . . .
or does this just run into the same problem as looking for the name of an object?
Maybe you should describe what exactly it is that you're trying to accomplish
I'm assuming that you're actually trying to limit what you can hit.
it's up here
@balmy vortex the idea is, different objects you collide with have different responses / behavior?
What do you want to do with the object your rays hit?
hey guys is there somthing like a nav mesh for 2D ?
I want to make the enemies track the player at all times and navigate around obstacles in the way instad of "walking" into the obstacle because the playeer is behind it
there's a navmesh plus package on github that makes unity's navmesh work for 2d, or there's aron granberg's A* Pathfinding Project which is another common alternative for 2d pathfinding (it also works for 3d)
can get a little more complicated to define whats walkable and what is not with 2d
in the past i would just roll my own A* that works off of a grid or quad tree instead of a mesh and use extra properties on tilemap tiles to define whats walkable
is there a way to delete a specific item from an array without the index, or am i going to have to find the index somehow
i'm going to be cloning gameobjects, putting them in an array to keep track of them and removing them when the object is destroyed
and i can't find too much on array functions in c#/unity
all i'm finding is that it's not as good as python's
use a list, and there is a .Remove function where you can just pass the object to remove from the list
oh
i couldn't find that on the documentation
i'm getting an error
it's saying "GameObject[] does not contain a definition for 'Remove'"
or Add
are they not capitalised
Remove is on list not on your object
use a list
oh
i don't know how to declare a list
i googled it and tried the first result i found and it didn't work
discord on my laptop is loading slow so it might take me a minute
you should really do some c# basics then, there are resources pinned in the channel. theres also tons of tutorials out there if you search anything related to "list c#"
well i've been learning c# for like a year or two now
i guess codeninjas is just shit then
before i was doing it like this:
public GameObject[] activeCoins;
but that doesn't give me the right results
🤷♂️ take a minute and actually explain what result you're expecting to see. stuff like "didnt work" is incredibly vague and no one can help based off such information
that's an array not a list
array has a fixed size, list is dynamic
if you've been learning this way for a year or two, and you dont know the differences between arrays/lists, you should find a new resource to learn from. Do some c# basics outside of unity
oh that makes sense
well then what am i doing wrong with declaring my list?
it's saying there is no such namespace as list
Import the namespace
from where
Do you use rider
what's that

