#๐ปโcode-beginner
1 messages ยท Page 541 of 1
https://hatebin.com/jsurafomkp when i launch my game the muzzle effect keeps playing even if i don't shoot
im trying to use lerp so the camera follows the player but for some reson it doesnt work properly ingame
I asked the same thing just rn xD
oh lol
I'll dm u the code I did which ended up working
Is "Play on Awake" enabled in the Particle System?
sure
no
UpThis
What about looping?
no
Will be good if you added a muzzleEffect.GetComponent<ParticleSystem>().Stop(); too.
Try adding this to your Update
if (!isShooting && muzzleEffect.GetComponent<ParticleSystem>().isPlaying)
{
muzzleEffect.GetComponent<ParticleSystem>().Stop();
}
And update the first line of FireWeapon() to this and try:
if (!muzzleEffect.GetComponent<ParticleSystem>().isPlaying)
{
muzzleEffect.GetComponent<ParticleSystem>().Play();
}
Just try these and see if it works
It will also make your code cleaner if you accepted a ParticleSystem instead of a GameObject for muzzleEffect lmaoo
it made it so that if I click it starts but when i click again it stops and in between it just keeps going
Ohhh
Hmm, it would be easier for me to Debug if I could replicate the project xD I guess you need to wait for someone who can debug stuff through code itself
But I assume it's because the Particle System State is not aligning with the isShooting state. Or the .isPlaying is not working as intended.
Why not set a global bool instead of relying on getcomponent in update (bad idea) and the isPlaying state that could lack behind
I canโt wait to share this good news, it turns out that I was just overthinking it. When I moved ImageElement.cs from Assets/Editor/UI to Assets/UI, the problem was solved.๐
Is there a way to reference a prefab from a prefab's instance?
only in editor code, not at runtime
aye need some help, how do i take a seed and make it into a random number?
let's say my seed is 9173617199 and i want it to give me a random number between 1-20, how do i go about this?
i think i can see the vision thanks
Agreed, Update() should be the thiniest possible, it's for time related variables and inputs on top. Getting a component at update for only few objects is okay i guess though.
If the GetComponent is getting the same component every frame, then it's pointless. Do it elsewhere so it can be called just once
The point is that GetComponent is a heavy operation and doing it every frame is a bad idea
You can get away with quite a few things in an Update frame because C# is generally very performant. However, if you are going to waste it getting a component every frame instead of caching then that does add up eventually
Hi, i've question for a code :
How to create a procedural animation for a game character ? (i've don't know how to create this, i've searched a tutorial, but i've don't fund)
What kind of animation are you looking for? There are some easy ways to do common proc anim tasks with humanoid characters.
Walk, and move, but it's for humanoid characters and multi-legged characters (and maybe crawling or flying characters)
I've done multi-legged characters using the animation rigging pacakge, let me find a link.
Take a look at the two bone IK constraint example in there,
in procedural animation ?
yes, procedural walking animation for bipeds and quadrupeds
i've don't understand what's that
oh ok
does OnClick() for buttons run the method given whenever it is pressed, or only the first time it is pressed?
if you're looking for tutorials you can search for 'unity animation rigging'
because right now it's only running the code the first time I click the button
ok and, if u explain at me ? (if u want and u can)
Whenever
animation rigging is a package that lets you do lots of cool procedural animation tricks on preconfigured rigs, I would suggest you learn some about IK (inverse kinematics) which is used a lot for moving bones realistically towards a target, it lets you animate where you want the feet (procedurally or otherwise) and then the package handles moving all the other bones
take a look at these images and then look up a proper tutorial
ok very thx ๐
RoundManager roundManger;
public TMP_Text mainTableText;
void Start()
{
roundManger = FindFirstObjectByType<RoundManager>();
}
void Update()
{
mainTableText.SetText("Round " + roundManger.Round);
}
Why am i getting a NullRefrenceExeption even tho the code works completely fine and shows no compiler errors. It can grab any Data from mainTableText and roundManager without issues
first off which line has the nullreferenceexception?
sorry, first line in the Update Method
Null reference exceptions aren't related to compiler errors. If the text gets updated then you have the component on more than one object, or twice on one object
In the start function, the find function returns null but doesn't give an error
You'll need to think of another way to get the round manager
There is another script using the exact same way of grabbing the roundManager Data. Could this be the issue when using FindFirstObjectByType?
Ill look into it! Thank you!
To answer this, nope the other script finding RoundManager isn't the problem here.
It's probably because you're calling findfirstobjectbytype before roundmanager is created
today I learned that TMP_Text has SetText
i got this and health is a slider i want to make sure to bind it to my enemy and see it in the world but can t seem to bind the image only the canvas
ive got a question to events
lets say i have a couple of brick objects. they all have the same script running on them. random variation may occur.
if one of these bricks is destroyed, i invoke a signal
public delegate void BrickDestroyed(BrickBase brick, int points);
public static event BrickDestroyed OnBrickDestroyed;
private void Hit()
{
if (remainingHits <= 0 || brickState < 0)
{
gameObject.SetActive(false);
OnBrickDestroyed?.Invoke(this, points);
}
}
but from what ive witnessed. this signal is called for all bricks on the screen and not just for the one destroyed.
private void Spawn()
{
collectable.GetComponent<SpriteRenderer>().sprite = collectableSprite;
Instantiate(collectable, transform.parent.position, Quaternion.identity, transform.parent);
}
private void OnEnable()
{
BrickBase.OnBrickDestroyed += CheckForSpawn;
}
private void OnDisable()
{
Physics2D.queriesStartInColliders = true;
BrickBase.OnBrickDestroyed -= CheckForSpawn;```
so in this example code, it would instantiate an object on all bricks on the screen. this is why i check for the brick.
but i still dont want all the bricks to fire the signal. is there a best practice way to write signals in a way, so they only get invoked from one single object?
Is this in world space UI? You should make a script that sets the position of the healthbar
Just parenting it won't work
got this right now
but images don t work seems only to work on gameobject
so sort of need the object and the image
it's very hard, i don't understand how to function ;-; i test every time, but my test not function
I need bones for this to work?
because OnBrickDestroyed is static, the event belongs to the class, not each instance of the class. as you can see, you had to reference OnBrickDestroyed through the class name BrickBase.OnBrickDestroyed, not from an instance. using the static modifier means there is only one copy of the field . . .
oh i see. but that only shifts the problem to having to know the component of the sender.
i guess ill have to build a whole listener system
If you pass the instance to the delegate function, your listeners can check if instance == this to see if they're the one that got destroyed.
Yes, a rig, or a tranform heierachy will do, don't forget to add a rig builder somwhere
i'm lost....
Take a look at the rigging workflow docs: https://docs.unity3d.com/Packages/com.unity.animation.rigging@1.3/manual/RiggingWorkflow.html
you can pass the brick instance to the event and check if it's the correct one . . .
also, this looks like #๐โanimation, not coding . . .
oh sorry, i was thinking of coding the procedural animation at first
good thx
so i go to this chanel ?
as uldynia mentioned, you position/move the ui differently if the canvas is screen space - overlay or world space . . .
that channel is specific for animation. they have more information and resources for animation/rigging than a coding channel . . .
oh, ok thx ^^
?it just doesn t update yet and dunno how to update it
anyone?
am I understanding correctly that you want to update a world space UI element?
We can't help without seeing your code, but first, have you tried following a tutorial for creating or updating screen space UI or world space UI (whichever one you're using)? It's a popular topic, so there are many . . .
yeah have tried
yeah
You'll need to keep a reference to the instantiated object, and I suggest a gameobject to assign and expose the bits you want to change to make it simpler.
public void ApplyDamage(EnemyData enemy, int damage)
{
if (enemy == null)
{
Debug.LogError("Enemy is null!");
return;
}
enemy.MinHealth -= damage;
enemy.MinHealth = Mathf.Clamp(enemy.MinHealth, 0, enemy.MaxHealth);
Debug.Log($"Enemy health after damage: {enemy.MinHealth}/{enemy.MaxHealth}");
UpdateHealthBar(enemy);
if (enemy.MinHealth <= 0)
{
Debug.Log("Enemy health reached 0, removing enemy...");
if (enemy.spriteRenderer != null)
{
Destroy(enemy.spriteRenderer.gameObject);
}
if (enemy.healthBarImage != null)
{
Destroy(enemy.healthBarImage.transform.parent.gameObject);
}
temporaryEnemies.Remove(enemy);
}
}
public void UpdateHealthBar(EnemyData enemy)
{
if (enemy.healthBarImage != null)
{
float healthPercentage = enemy.MinHealth / enemy.MaxHealth;
Debug.Log($"Updating healthbar: {healthPercentage * 100}% health");
// Stel de fillAmount correct in
enemy.healthBarImage.fillAmount = healthPercentage;
}
else
{
Debug.LogError("Healthbar Image is null!");
}
}
}
all debug logs work just can get the fillamount working
It doesn't look like you're saving a reference to the health bar anywhere when you instantiate it so how is it you are trying to update the image later?
Where do these references come from:
enemy.healthBarImage```
yeah that ^
You are only saving the reference in a local variable which quickly disappears
My guess is you are modifying the prefab instead of the actual instance you created in the scene
This doesn't make sense - how would this refer to the instantiated prefab then?
It seems like you're just referencing the prefab with these fields in the inspector
so it makes sense the code doesn't do anything
How is this assigned?
Where do you assign the healthBarImage?
newEnemyData.healthBarImage = healthImage;
so where does healthImage come from?
why don't you just show the full script. And not with screenshots
!code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Image healthImage = healthBarObj.GetComponentInChildren<Image>();
and where does healthBarObj come from...
show full code instead of playing this game
if it's all set up correctly I'd double check the Image.type is set to Image.Type.Filled
but if i drop the full code is it safe against plagiat cuz don t want my code to be plagiat cuz i dropped it here first
Nobody is going to steal your code that doesn't even work
and also wouldn't be applicable to anyone else's game
it is not about stealing it is about handing it in later and then i get in trouble cuz the teachers think someone else wrote it
I don't know anything about your teachers' plagiarism detection methods
can t i just sent 2 big code blocks?
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Enemy : MonoBehaviour
{
[System.Serializable]
public class EnemyData
{
public SpriteRenderer spriteRenderer;
public float speed = 2f;
public float MinHealth = 100;
public int MaxHealth = 100;
[HideInInspector] public int currentWaypointIndex = 0;
public Image healthBarImage;
}
public List<EnemyData> enemies = new List<EnemyData>();
public Transform[] waypoints;
private List<EnemyData> temporaryEnemies = new List<EnemyData>();
public GameObject HealthBarPrefab;
void Start()
{
if (enemies.Count > 0)
{
SetEnemy(0);
}
}
void Update()
{
foreach (var enemy in enemies)
{
if (enemy.spriteRenderer != null)
{
MoveToWaypoint(enemy);
}
}
for (int i = temporaryEnemies.Count - 1; i >= 0; i--)
{
var tempEnemy = temporaryEnemies[i];
if (tempEnemy.spriteRenderer != null)
{
if (MoveToWaypoint(tempEnemy))
{
Destroy(tempEnemy.spriteRenderer.gameObject);
temporaryEnemies.RemoveAt(i);
}
}
}
}
public void SetEnemy(int index)
{
if (index < 0 || index >= enemies.Count)
{
Debug.LogError("Ongeldig vijand-index!");
return;
}
}
shitt i need 3
Please use a paste site.
as described here
but scared i get plagiat bullshit then and then i did all for nothing :/
using a paste site will be equivalent to posting all of the code in here
yeah but then it is on the web here im directly bind to it
Do you think people steal code from random pastes?
Yo does anyone have any links to a good intro to coding. I know โhow toโ but the actual writing of code is confusing. Just started yesterday
particularly private ones..
no it is about handing it in with plagarism like i said before
guess you don t understand the point
I don't think we do
yeah me neither tbh
They are afraid their professor's plagiarism scanner will see the paste online and then detect their homework as plagiarism
You appear to be concerned that a plagiarism detector will dig through every single paste every made on any paste site
Plagiarism detection is not going to find random pastes
Oh.
I'm so out of the loop when it comes to this stuff
That's a real concern?
I have no idea!
Honestly I have no idea, it might be a legit concern
notably, non-public pastes are very hard to randomly find..
yeah cuz then i can throw my whole project away
There's no public list of these pastes, so I very much doubt it would matter
Change the names of variables? The spacing? Comments?
is this actually grounded in reality
or is this just something you heard of once from A Guy
It's very hard not to have near identical code to something else online, even if you're not intending to.
a good plagiariam detector would pick up on that ๐
just use https://paste.ofcode.org and get on with it
regardless, without seeing any code we can't determine what/where the problem lies and how to fix it. i doubt posting code will ruin your assignment . . .
by chance of python 10s of hours to 0?
maybe i should encrypt it and tell the pw in here 
Just use the damn site. It doesn't have a public list of all pastes and everything gets deleted after a week
This is a complete non-issue
Reminds me of the plagiarism detector that didn't like the word "The"
ok but if not i will come after you ๐
done
did you double check the Image.type is set to Image.Type.Filled?
when you instantiate the health bar set the .fillAmount to Random.value
and just check to see if it's working at all
you should check that you're getting the correct image. perhaps there are multiple images
you could do this by logging the Image you get
sure but i have 1 health
if so, it would be preferable to make a Healthbar component that you reference instead of a plain GameObject. It could tell you where the actual fill image is.
this didn t work
also comment out your UpdateHealthBar body
if it works after that then you're calculating the fillammount value incorrectly
Debug.Log($"{HealthBarPrefab}");
like this?
how would i do that?
no like this
so comment everything out?
yes, set the value to a random amount and then don't change it, then tell us what you see
but in the func itself ?
set it when you instantiate,
I want to be able to control the player with wasd and this is my code:
horizontalInput = Input.GetAxis("Horizontal");
verticalInput = Input.GetAxis("Vertical");
transform.Translate(Vector3.right * horizontalInput * speed * Time.deltaTime);
transform.Translate(Vector3.forward * verticalInput * speed * Time.deltaTime);
Problem is when I rotate the player, its z axis changes direction and the controls are very weird then. Can anyone help me?
Do you want the player to move in the same direction no matter how the player is rotated?
perhaps you want transform.right rather than vector3.right
Translate is already working in the object's "self" space
It is correct to give it fixed "right" and "forward" vectors here
yes, I want to make a top down shooter game and I need to set up player rotating in the direction of mouse and that the player doesnt move like a car.
In that case, use Space.World as a second argument to Translate
oh yeah it has a optional param for Space
oh ok ill try that ty :)
This tells it to interpret that vector as a world-space direction
instead of a local-space direction
now it doesn t wanna work anymore :/
one learns something new every day 
argument?
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/method-parameters
TLDR arguement / parameter of a function
egvoid Move( arg1, arg2, etc.)
You have imported the wrong Random.
you probably have a using System; at the top of your file
You can just write UnityEngine.Random to make it very explicit that you want unity's Random class
๐คฃ
You can remove using Unity.Mathematics;, which will then make the IDE ask you which class you meant to use
or you can explicitly use UnityEngine.Random
btw you can also just do using Random = UnityEngine.Random
That too, yes.
using directives let you avoid writing out all of the namespaces for a class
using Foo.Bar.Baz means you can write Buz instead of Foo.Bar.Baz.Buz
While you're at it, consider logging which Image you're actually targeting here.
Debug.Log(enemy.healthBarImage, enemy.healthBarImage);
the second argument is the "context". You can click on the log entry to go to that object
I suspect the image you have reference to isn't the right one then
While you're still in play mode, click on the log and see what you're actually getting
I bet you got the frame image
Which is why GetComponentInChildren is evil and will break your project in new and surprising ways at random!
I had a killer bug where GetComponentInChildren<Renderer> wound up grabbing a VisualEffect instead of a MeshRenderer. My code wound up breaking the visual effect, and I couldn't understand why it was failing to play
now I will retrieve my wall of text I was typing earlier!
I tend to make a monobehaviour which explicitly publicly exposes the bits of the UI I care about and attach this to the prefab, assign them manually
Instead of using GetComponentInChildren, you can make a component that talks to the components for you.
public class Healthbar : MonoBehaviour {
[SerializeField] private Image fillImage;
public void SetHealth(float percentage) {
fillImage.fillAmount = percentage;
}
}
Make a prefab that has a Healthbar on it. Assign the correct reference.
Then, your creation method would look more like this:
Healthbar newBar = Instantiate(HealthBarPrefab, newEnemy.transform);
newBar.transform.localPosition = new Vector3(0, 0.5f, 0);
newEnemyData.healthbar = newBar;
UpdateHealthBar(newEnemyData);
}
You would also need to store a Healthbar instead of an Image on the enemy data.
You no longer talk directly to an Image. You just tell your Healthbar that it needs to display a certain health percentage.
sadly we still don't have an argument for GetComponentInChildren / Parent to skip the root object too
I know how to fix it! Never use it ๐
I only use GetComponentsInChildren
GetComponentInParent is generally less surprising
just because you only have a few parents, but can have many, many children
HealthBarPrefab's type would no longer be GameObject. You'd change it to Healthbar
so first step is making a prefab adjusting health seems so simple but 3 hours stuck on it lol :/
It's simple, but you footgunned yourself with GetComponentInChildren
It gave you the first component it could find on the object
It's just...the wrong component
Which is why I try to avoid it as much as possible. Your code shouldn't care about the exact order of components on an object (or the order of its children)
f i see
whats the best ide for c# and python
VS , Rider or VSCode
thought thats for python
yeah so i can fix it with changing orders but that is just the cursed solution
Right. It might break later for very subtle reasons
like if you add another Image to show the previous health value
For C# you use Visual Studio or Jetbrains Rider.
For Python you use Jetbrains Pycharm.
Jetbrains is just the company that makes many different editors
Also, by doing this, you'll be able to keep all of the healthbar logic in the healthbar
thanks and noted
If you want it to slowly drain over time, that's very easy. The game will just call SetHealth on it, and it'll decide how to change the image's fill amount over time!
okay so what are the steps basically ๐ ( it is based on the towers hitting)
I have several components that started out as "bags of references" -- no logic, just public fields -- that then got more features
well, focus on getting the healthbar working first (:
Create your healthbar component and put it onto the existing object. Reference the correct image component.
yeah that works already what are the steps for the healtbar 1 make a prefab from the canvas and then?
You're already instantiating prefabs, right?
or are you just instantiating an object that's in the scene?
the towers and projectiles from the towers are prefabs the rest isn t
Okay, then start by actually making a prefab
you can just drag the healthbar template into the Project window to create a prefab
Then, after adding the Healthbar component, update your scripts to reference a Healthbar, not a GameObject or an Image
and then assign a reference to the prefab where needed
will try thank you
I almost never reference prefabs as a GameObject -- that implies I could use any prefab!
Click-to-Move (Camera Jitter)
tried object but can t seem to find the right type to fix it
"tried object"?
Object
but the heatlbar image needs image in order for the slider to work and the child thingy is a bit annoying to get rid of
that's even less specific!
use Healthbar
the point is that you reference the prefab as a Healthbar
super stupid but dunno what im suppose to do ๐
oh so you create a custom script for it in other to find it was like how is it suppose to find it ๐

Yes -- you're creating a new component called Healthbar
Hey, so apparently i've tried anything to make my animation loop, but it just doesn't work. I mean, i might know why, but don't know how to fix it.
The idle animation, which i set up as default state, exit time is off for the transitions that should be off, like moving animation and idle animation. So it should be right.
"'Player' AnimationEvent has no function specified" error shows up.
Any ideas?
did you set the actual animation clip to loop?
yes i did
the error means you have an animation event on the animation clip but did not specify a function (method on a script attached to the GameObject) to play when the timeline reaches the animation event . . .
not that i know of . . .
let me check rq
check the clip for an animation event. if you don't need it, remove it . . .
The animation plays really slow, doesn't play or just stops and doesn't animate any other things.
What is the appropriate wait time before reposting if I don't see a response to my help request?
It's not like everyone knows the answer to your question, but you can try at some kinda 10min-ish interval
ohhhh wait
forgot about those
there's like
999+ warnings
you can post a bump to your question by replying to the original message or repost it altogether . . .
Sorry I don't discord a lot, how do I bump my thread?
the chat moves fast and if it's been a while, no one will know you had a question or remember . . .
bump . . .
Alright, basically i fixed the reason of warnings, but the animation still feels slow and stops itself after a moment. No idea why.
just hit/select reply on your original question (message) and put any text you want, like, "bump," or "here's my original question if anyone can help," or just repost the question altogether . . .
Camera Movement (Camera Jitter)
Slope Movement Issues
if it doesn't involve code and it's just the animation, i'm unsure what could be wrong. we have no way of seeing what the problem is . . .
bump
can you show me the script?
or the inside of a button or however you call it
js dm if you cant send it here imma look for it
i only started recently coding in c#, but i think the #if, #else and #endif seems interfering with the editor.
my exitgame looks simple
public void ExitGame()
{
Application.Quit();
Debug.Log("Game Closed");
}
}
but yours is kinda complicated
that is because your code will not do anything in the editor play mode, his will
this is just the code my prof gave me so i assume theres nothing wrong with the script itself
welp i have no idea then
Add some more Debugging, make a development build then check the player log
Hi! I am working on a top down shooter\survival game but I don't know how to make the players gun face the mouse, here is my attempt at this:
mousePosX = Input.GetAxis("Mouse X");
transform.Rotate(0, mousePosX * sensitivity, 0);
get the mouse world position, then set your forward with direction (mouseWorldPos - gunPos)
i feel the lobotomy effect rn
Vector3s, in fact, cannot be changed. Changing any of them creates a new Vector3 every time
yes you're fine. not something you should worry with. Vector3 is efficient its a struct with 3 floats.
oh okay thanks! and digiholic also
They're structs, they're designed to be created and disposed of freely
i actually feel like lobotomy effect rn
I... don't know anything about that. I don't know how to get the mouse world position and I don't know what "set your forward with direction" means ๐
Vector3 worldPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
thats what we call Developement, problem solving. See how you have each part you can ask, look at things like google chances are someone already asked those questions and the solutions are right there
why do I need to get the main camera for this?
3D or 2D game?
The relationship between your screen and the world depends on where the main camera is
Like how is your world oriented
i have 600 objects whats cheaper looping them all every frame to check which is closest or strap collider to each of them and do ontriggerenter
The code suggest 3D game since you tried to rotate on Y axis
i assume second one
think of it like shooting a ray From ur camera thru the mouse position and into the world
why not do some profiling and test, instead of guessing ?
3D
Orthographic or perspective camera?
orthographic. I wanted to make an fps game at first but when I looked up tutorials for fps camera I felt like I got brainfreeze.
still not having any luck, i didnt see anything of note in the player log
With ortho, ScreenToWorldPoint should be fine but be mindful of the y position
Like if you create a direction vector with mouseWorldPos - playerPos, set the y to zero
At least if you use it for projectiles... If you use it just for y angle then it's probably fine
wait, so now I have got the world position and the mouse position, how do I get the player to face that point?
transform.forward = dir
Hello, I'm new in the unity world (from webgl) and I have a question. I hope this is the right place to ask for some advices!
I'm creating to understand unity some single pages like in the web and for that I use UI Document. To "catch" a click event on buttons in C# I do this (on my screen). But I'm not "sure" about the right way, is this OK ?
seems correct though
also you should probably configure your VSC
you might understand your code better if you did not use var
i agree w/ steve here.. try to limit ur use of var
if u know what type it is go ahead and assign it to the correct type..
Ok thanks for ur advices, I'll limit the use of "var"!
Hi, can someone help me what to do with this kind of error?
scripts had compiler errors, fix them?
how if you haven't shown all the errors?
this is the only one
did you check which scripts have compile errors?
screenshot entire console window
are their any other errors messages in your console window?
there is no specification
I'll show you
new error apeared for no reason? What does that mean?
the error was always there, you just didn't look
i'd checkout that first error . . .
I'm telling you the truth
fixed errors mean more of your script(s) compiled further until they reached another error . . .
keep fixing them until they all disappear . . .
I'd like to but what does that mean the transparency thing
also these errors should be appearing in your IDE, if its not I'd configure that first
I believe this happens if you previously had a syntax error
I'm pretty sure the compiler just gives up on further analysis
(which can result it finding non-syntax errors, like that one)
It is not apearing because I was trying to build the game
Ah, I know what it is, then
the IDE has 0 to do with building the game
You've got editor code that's getting included in the game
then why are you telling me about ide
Editor code should go into a folder named Editor. That will put it into a different assembly that doesn't go into the build
When you build the game, the UnityEditor namespace is not available. Any code that tries to use that got included in the built game will fail to compile.
Importantly, you will not see this in the IDE, because it still thinks it's analyzing code for use in the editor
because usually compiler errors are underlined in IDE
Does that mean I have to move the Texture Maker to some kind of folder named Editor?
Yes. It can be a subfolder if you want, but it needs to be inside a folder named Editor
I'm desprate about this. ChatGPT won't help in this
Do you mean in project folder or in the installed editor?
I'm sorry it is too late for me
e.g.
If it doesn't exist, you'll have to make it.
Okay
you need to create the folder if it doesn't already exist, yes
fen do you see anything weird i am unable to select my healthbar
the name must be exactly Editor
there is no Healthbar in the scene
which is reasonable
Annoyingly, if you switch to "Assets", it won't show you the prefab you made
apparently it's a performance concern
You'll have to drag the prefab into the property in the inspector
it doesn t wanna do that either
Then your prefab doesn't have a Healthbar component on it
huh but i don t need the script 3x im confused
3 times
You need to attach a Healthbar component to your prefab
If you don't, then there is no Healthbar to reference at all
and how does enemy know that then?
know what?
the health because now it is only bind to the prefab
"the health"?
The enemy class has a HealthBarPrefab field on it
This lets you store a reference to a Healthbar
Drag the prefab into this property in the enemy's inspector
Im tryna make a script which tries to get the layer of the object it collided with. I use a LayerMask for EnemyLayer but its not working lol:
void OnCollisionEnter2D(Collision2D collision){ //Called whenever object collides with another object
if (collision.gameObject.layer == EnemyLayer){
Debug.Log("Enemy Hit");
}
Destroy(gameObject); //Destroys bullet object
}```
.layer will not be compatible with a LayerMask
the layer property is a number from 0 to 31
like this?
a layermask can be any integer (each bit represents a layer)
So i need index of layer?
oh ok
You haven't dragged in a prefab yet
Annoyingly, LayerMask doesn't have a convenient method for this
if (mask & (1 << whatever.layer) != 0) {
}
alright thanks
This tests if the mask has the relevant bit set
Layermasks are a bit weird, but this goes over what they actually are under the hood.
https://unity.huh.how/bitmasks
You can turn an index into a mask by bit shifting 1 by the index, as Fen just posted
A bitmask is a representation of many states as a single value.
i did the one below but those 2 above shouldn t be the same ?
Oh, there's a prefab field, but also an Image field in both of the enemies
So, you've got your prefab referenced now at least
Ah, I see what you're talking about.
You don't need to assign anything here
These fields are getting filled in by your script as you spawn enemies
I would suggest adding [System.NonSerialized] to them so they don't even appear in the inspector
(and so that they don't get saved at all, ever)
Serialized fields are used to configure an object in the inspector, but you aren't doing that for the "Health Bar Image" field. Your code sets that field.
alright thank you so much think i am almost done with the core features ๐คฉ
now need to find out why i can t see the projectiles (prob go too fast) but that is a problem for tomorrow ๐
is anyone able to help 
Try changing the size of your game view (put it on Free Aspect and resize the view, and also try different resolutions)
Your UI is probably not scaling properly, causing something to get in the way of the buttons
ah yup!
Show your setup in #๐ฒโui-ux. I suspect you'll need to adjust some anchor points
Ideally, turn stuff off until you have one button and one other object that makes the button unclickable
(and the canvas, of course)
more people need to do this when troubleshooting.. ^
i see soo many times w/ sooo much stuff going on in the background its hard to know what the problem actually is..
and ofc u got ur long compile times to wait thru to show a video clip ๐
i would be really happy if anyone would be willing to give out an helping hand. so i am working on a ready or not CQB FPS style game and ive been stuck on this issue for a week now for some reason the bullets sort of stick to the gun and pushes the other bullets out making them fly out and thats making the bullest fly slower than what they are supposed to be so what i did was that i tried to make a colliding checking system as to not make the bullets collide with eachother now the bullets just dont fire and are just stuck in the barrel ive also tried rotating and fixing the bullet spawn point but at some angles the bullets just dissapear just when they spawn. if anyone is willing to help i will be very happy.
Well, for the collision problem you can just remove projectile colliding with other projectiles via collision matrix in the settings, or just exclude the layer on each bullet rigidbody
make sure ur bullets are ignoring themselves.. (other bullets)
could use layer-based collision solutions..
very common occurance if u have a high fire rate..
probably ignore guns too I guess if it's spawning inside
could be clipping the gun's collider as well
haha, same page
honestly I would just make them kinematic too, but I guess you lose on on the collision detection interpolation
and collision callback I guess
I would not let the physics system move my bullets at all
yeah, but those collision callbacks giving to the exact point is pretty gooood
I'd be doing raycasts forward to figure out what's in the way (doing very small steps)
certainly not updating just 50 times per second
even with rigidbody detection, stuff likes to clip through walls a lot for higher speed projectiles
Random example -- H3VR does raycasts to move bullets forward by a bit at a time
(i think, at least; been a hot minute since i modded that)
like if you're shooting a bullet at 100 units a second, you might as well make it hitscan cause the next frame it's probably going to hit anyway
unless you're doing some battlefield type game. I'm pretty sure most of that is actual projectiles
bullet drop!
the horrors
worked on an Anti-Aircraft type gun earlier this year.. i had problems just like that.. bullets colliding w/ bullets.. then colliding w/ the gun barrel.. etc.. **edit: nevermind it seems i just offset the firing position well in front of the gun, not sure that would work for your situation since its personal arms.. and will probably fire at closer proximity to other things, might not be the most accurate)
i couldn't use raycasts in order to get the desired effect (with bullets creating that arc), well now that i think about it i probably could.. but i just used rigidbodies.. still need to build a pooling system for them tho..
lol.. i used exactly 100 for my bullets ๐
i havent done much of any testing tbh after getting it firing correctly.. (not sure what kind of physics issues a projectile moving 100 units / second causes)
rb physics does an ok job, but at 100 I'd have 1 clipping through every so often
true, true.. since my target is 100s of units away i dont have those issues
may just want to do your own raycast checking if that happens
the bullet has a CHUNKY collider.. and continuous dynamic i think
yup, thats all.. unity's physics engine does the rest ๐ช
i hate certain things like wheel colliders for example.. but i have to say. Unity's physics engine is pretty nice most of the times i deal w/ it
yeah it's pretty decent. I've kinda just use the KCC for everything nowadays though
can't be bothered with the game physics parts like moving platforms and slopes ;)
i have a paid variant of it.. and i can agree.. kinematics are the way to go when player characters are involved
i swap from that and a CC
I have ecm2 as well which is identical but havent used it much
I'd say it's more like the continued supported version of KCC
Character Movement Fundamentals is the one I use. No real complaints so far
i think that cool capsule w/ a cap caused me to impulse purchase ๐
is KCC not getting updates/supported anymore?
or did i read that wrong
looks pretty good. If I had all the money in the world to buy the 30+ cc solutions on the store I would
KCC is released free but unsupported now as the dev got hired by unity
I think he probably got paid for making it free too
oh okay
he makes the CC for entities I think
sorry for the late answer i was eating dinner, thank you a lot for all the answers ill try all of them and see what works!
So I tried to understand how "singleton" works, and I still don't understand, also I tried to understand how static class work and I don't really understand etheir , so I just try to remove the "static" when I instanciate my class
//I changed this
public static Client Instance { get; private set; }
// to this
public Client Instance { get; private set; }
and it seam to work completly fine, and hasn't changed anything, but when I'm trying to call the "Died()" void from my Client script I still have this issues, even if nothing is static anymore (or at least I think nothing is static)
Assets\_Script\Multiplayer\Client.cs(335,29): error CS0120: An object reference is required for the non-static field, method, or property 'FPSController.Died()'
its not a singleton if its not static. make it static
and then call FPSController.Instance.Died()
why do you add .Instance when calling this void ?
thats how you access the singleton
Singleton isn't truely static... you can always renew the instance inside of it and get a whole fresh new state
they have some uses over static classes though which you should use if it's not just static read-only data or simple global utility methods
okay that's it, I'm now completely lost ๐
puting them on a monobehaviour and throwing it on the scene will allow to serialize values right onto it too so really helpful for setting up the scene to a main manager type system
but, the script where is my Died() void isn't a singleton ?!
Here is a simple example to help you understand Singletons:
public class ScriptA : MonoBehaviour
{
public static ScriptA Instance;
private void Awake()
{
if(Instance != null)
{
Destroy(gameObject);
}
else
{
Instance = this;
}
}
public void Die()
{
Debug.Log("Die");
}
}
public class ScriptB : MonoBehaviour
{
void Start()
{
ScriptA.Instance.Die();
}
}
static classes only come in scope when they are first referenced, but mono singletons will only scope when you choose so (usually on scene load)
I kind of understand what you're doing, but in my case, it would be the scriptA instance that try to call a void in the scriptB
you're turning your script into a singleton, not the methods inside it (the void thing is called a method)
Sorry, can't really discuss it because it's late here but I think the others explain it very well
hey, im new to unity and making a game for a school project. I found and learnt this code for a following camera, but i cant seem to edit it to make the camera only follow on the x axis. any help would be appreicated :).
don't worry, and thank you so much for helping me yesterday!
obligatory: use cinemachine
only update the x axis then ;p
Having trouble adding a force to a prefab instatiated from code. Im declaring a public Gameobject and assigning it in the editor to my prefab. im then running a method that instantiates the prefab how I want but wont apply a force to the Rigidbody?
I'm really sorry, but I didn't understand what you meant.
show !code but i'd bet you're trying to apply force to the prefab rather than the instantiated object
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
what do you think a singleton is?
yeah I figured, I dont really understand the code at the moment so im not sure which specific bit is affecting the x and y axis
to be honest, I have no idea
So if the hole class is static that means all methods in the class are also static.
So all you need to do is
public static void DiedUI()
{
PlayerUI.gameObject.SetActive(false);
LeaderBoard.gameObject.SetActive(false);
DeathUI.gameObject.SetActive(true);
}
public class ShipCoreSpawner : MonoBehaviour
{
public GameObject LaserShot;
public void FireCannon()
{
Instantiate(LaserShot);
Rigidbody rbS = LaserShot.GetComponent<Rigidbody>();
rbS.AddForce(Vector3.Forward * 200f);
}
void Update()
{
FireCannon();
}
}
this is the summerized version
yep, you're adding force on the prefab not the instantiated object. Instantiate returns the newly instantiated object so use that instead
You're setting a vector3 with another vector3. Check the properties of a vector3 to get an idea what you can access
don't forget, you cannot access instance fields, only access static fields as well . . .
LaserShot is the prefab, not the instantiated object you created. reference the instantiated object and use that instead . . .
whats that reference called / how is it accesed?
check the !docs for Instantiate to see how the method is used . . .
you access it the same way you access the returned object from any method that returns an object. assign it to a local variable. if you do not know how to use a method to return an object, perhaps start with the beginner c# courses pinned in this channel
brainfart, ty
think of it as a way of accessing your script from anywhere without needing a reference. you know how scripts are usually referenced right?
I don't know if that's what you said (and I apologize if it is), but in the script where the Died() methode is, Nothing is static.
Also I already tried to set the Died() method as static but I get this error 3 time (one for each UI):
Assets\_Script\Character\FPSController.cs(476,9): error CS0120: An object reference is required for the non-static field, method, or property 'FPSController.PlayerUI'
im aware it refers to the x, y, z positions right? Im still confused with the code because it doesnt seem to be changing those positions seperately
It sets the whole vector, but you want to make a new vector with the previous yz units but with new updated x values. Just got to expand it out more.
have you done the beginner unity courses at !learn ?
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
Normally, I know, it's when you reference them directly via the inspector, or when you search for them on a specific object using the .find method. So if I've understood correctly, this means I can do exactly the same thing as when I reference my scripts, but without going through this referencing stage?
I think I never finished it. ๐
In update if you just want to update the X position it would be something like this crude in Update:
transform.position = Vector3.SmoothDamp(new Vector3(transform.position.x,0f,0f),new Vector3(target.position.x,0f,0f),ref velocity,smoothTime);
yeah you just call the .Instance to access its methods. and singletons can only be used for scripts that you have only one of
ohh that makes a lot more sense now how you can expand it. I will try that. Thanks everyone
that seams to be quite powerful and useful
true
I never thought that such a simple error could have taught me so many things, thank you so much for your help (on that note, I still have to find a way to display this UI ๐ ).
I purchased an asset with its source code provided and attempted to add new features using it. Upon reviewing the code, I discovered that most of its functionality is implemented without the virtual keyword, making it difficult to extend and use. I understand that such keywords should be used with clear intent, but there are parts where I genuinely believe inheritance is necessary.
How do you approach resolving such cases? Would it be appropriate to modify the asset's code to make it more extensible?
That would seem to be the approach, assuming there's no breaking updates to come with it.
You could always message the developer too?
It seems I need to look for the developerโs email. (It is not listed in the asset overview.)
I have a basic question, if i call this "for" function inside void Start() would the "for" run 3 times in a single frame?
Or would it complete it''s rrun in the third frame, meaning the "for" run incrementaly each frame?
{
for(int i = 0; i < 3; i++)
{
Instantiate(enemyPrefab, GenerateSpawnPos(), enemyPrefab.transform.rotation);
}
}```
loops do not happen "over time" like that, the entire loop is completed before the next line of code runs
if you want something to happen over a period of time, use a timer in update without a loop, or use a coroutine
It seems I can find the developer's email and contact them through it.
What's the asset?
A simple example to show that it doesn't happen over time, is with a while(true){}, which will freeze your app since it never escapes it. So code afterward doesn't execute.
All functions run to completion when called. Whenever you call SpawnEnemyWave, it will do the entire function before moving to the next line
support@meadowgames.com
you can look for their email by clicking on their name
Idk if this goes here but I have my player equip a wand. When I look left and right it rotates fine but up and down makes the wand weird. How would I make it rotate the same as left and right and also not look weird to other players
Hello!! im kinda new using unity and im getting so anoyed with the camara in the editor, rigth now i cant zoom in my objects and they are in the coords 0 0 0 and the editors camera is like soooo far out but it doesnt let me zoom in, like i can zoom out but when zooming in it just stops
it is required by unity to have some sort of way for others to get in contact with you
got it thanks!
thank you!
zoom out and select an object and press F to focus
omg thank youuu
it will move the editor camera near the object, of which you should be able to zoom in
yeees thank you, been more anyed with that camara than coding itself haha
It seems that modifying the code might be the best solution. I will discuss this issue with the developer. Thank you!
hey another question, this anoying error is there almost since i started the proyect, what is it?
Exactly what it says in the error. In one of your scripts your code is referencing and trying to do something to an object, but there is no object there for it to do anything with. If it's a public gameobject or something just assign it in inspector, or if it's not public then use GameObject.GetComponent to get the reference to the object.
is there a function for "return number thats further from 0"
ik theres piping abs into max but i'd rather it be inplace
and the only way i can think of to have that is multiplying it by the var's sign after which feels yucky
nvm got it
Sounds like this https://learn.microsoft.com/en-us/dotnet/api/system.mathf.round?view=net-9.0#system-mathf-round(system-single-system-int32-system-midpointrounding) with MidpointRounding.AwayFromZero, but might not be the same thing you want
So I've been having two issues I don't quite know how to fix
For one, I'm trying to build a game in the same aspect ratio for a phone, but for Windows, so I tried setting the resolution on Player Settings as 1080x1920, and 720x1280, and fullscreen mode as "WIndowed", both without success, as the game launches with a wider than intended screen
Any clues how I can fix this?
Vector3 worldPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.LookAt(worldPosition);
apparently I am doing this wrong. how do I make my character look at the mouse, but never look up or down. how?
you have to omit the y position
how
you assign the target Y pos to height you want
if thats sprites you have to probably make some code to adjust the sizes according to screen.height/width
(similar to how canvas scaling works in UI)
the camera resizes with the resolution, you probably did not align everything using the same res as your window/player build
even with the same aspect ratio you have more pixels
Hm, I wonder if that's related with the fact the Canvas I set doesn't appear with the title of the game either
you'd have to check your canvas scaling mode and whatnot
the resolutions you pick in game view mode are important for testing, after that they do not affect the player
The whole pixels per unit schtick?
ideally you would have Scale With Screen
then set a reference base resolution (eg if i target 16:9 i usually start at a low HD like 1280 x 720)
I probably didn't do either of those, lemme open the project and check some stuff to see if it helps
I think it's the typical case of "What I see in Game Mode I presume will be there in Build"
thats strictly UI btw, for sprites it gets tricky because there is no such component that does it for you
yea only if the resolutions fit the ratio you tested on
Eh, if anything I can just put some black boxes on the sides and call it a day, no biggie
also viable. Also you can check Screen class to see whats the current size for what you did in game view. If anything keep the window size around that rez
I think the Game worked because I specifically set it to be ran on a 9:16 ratio, while also keeping the camera to the same size
As for the Canvas, eh... red circle is where the sprites and stuff for the game are. I should probably screenshot the Canvas itself, no?
Yeah, I probably found the issue
One second
I dont know what it is!, literally it started saying that rigth before i started the new proyect, i ignore it and keep adding stuff, and what i have done is working fine, so it should be any of my objects, how can i know where is the error coming from?
It gave the error on a blank project with no scripts? Try double clicking the error to see where it takes you or what more info it says
also does it keep coming back if you delete the error?
Open your Package Manager and look for anything that needs to be updated
If it's a brand new project, could it be outdated ? ๐ค
Yeah, the templates don't get updated unless you reinstall the editor
Good to know, thanks
i just takes me here but thats part of unity itself
man idk sorry.
yes it does
try this
there was something that needed to be updated and i did it but still that error
literally this all i have
i mean what im doing still works but just wanted to get rid of that error
looks like a unity VC issue, if you need unitys VC make sure you have the package installed
can you search for the script in the project, select it and show the inspector please ?
delte unity version control
yes, if you do not need or want it you should not have it as it may cause issues like this.
Ohh
new blank templates are borked
where do i delete that?
you should be able to do so via package manager
just get rid of the version control package
give unity a restart too mayb
Yeess it worked
thank you guys!
Huh, now it's way too big
I just redid the Canvas as a whole and adjusted it with Scale with Screen, dunno what went wrong this time
whats it look like in game mode unity?
Still normal as it should look like
but what resolution are you testing.. like i said the Aspect ratio isn't the only factor
if its a bigger pixel area it has to compensate
Oh right. Currently it's 720x1280, that's prolly the issue
Lemme increase back to 1080p
Nnnnope, still big
where? whats is the resolution in the Game view and what resolution are you making build with
I'm using 1080x1920 for both, swapped the Aspect in Game view for the 1080x1920 outright
But when I tried to build, it's essentially the same image as I sent up here
also are you making a clean build each time ? and new folder?
Yup
I'll give it another shot in a different folder
Egh
Is it because it tries to emulate the big screen but my computer screen is not as big to fit it perhaps?
you have to anchor/resize things accordingly. Espcially the top logo
also you can tell the P and e Letters are pretty much the same distance from edges like you see them in game view.
So now it's just a game of resizing to fit in the frame?
and achoring
I frankly don't understand how the anchoring system-- thanks.
see link ๐
Yea, I was gonna ask about it as soon as you sent it lol
Mmm, I wish I could just see how big the thing actually is when I make the game, so I don't need to rebuild it all the time
thats what the game view is for lol
Well yeah, albeit when building it becomes different it's a little bit concerning
thats again, not proper layout / anchoring with UI will do that
for sprites, its a similar concept but there is no built component for sprite renderers
(canvas resizing i mean)
Hi! Is it possible to have an error in the unity console that isn't actually an error?
I was looking for a solution for 2 days to my error in my C# script, I left for about 1 hour to do other things, and miraculously when I came back my script was recompiled and no more errors appeared, even though I hadn't changed anything.
are you certain it was a compilation error in your code and not a runtime exception (including exceptions in editor code) or a warning?
wait do chars actually have 65k number capacity?
I don't really know, I was having this issue :
Assets\_Script\Character\FPSController.cs(476,9): error CS0120: An object reference is required for the non-static field, method, or property 'FPSController.PlayerUI'
C# chars are 2 bytes. The maximum unsigned integer that can be stored in 2 bytes is 65,535
That is a compile error, yes. and you had to have changed something to fix that. you likely either got a reference to the object or made PlayerUI static
What's on that line
I'm 100% sure I don't change anything
thats a lot of space inside single char i could mash in many data into string and extract char by char
char type has the size of 16 bits or up to 65,536 ( 2 1 6 ) unique pieces of data
and i'm 100% certain that you did because compilation errors don't magically fix themselves
Congratulations you've just discovered binary serialization
it never worked well with strings
i will have to base64 it each time i want to hold it
It works fine, as long as you don't care about your string actually containing anything readable
Yeah I know, that's why I was asking, because it seems to be a very strange situation.
What's on the line with the error
it was this line
fpsController.Died();
i guarantee that is not the line the error you just posted was referring to
The error you posted references PlayerUI
This line doesn't
so you probably changed more in the code which changed which line this was
ok so let me explain the whole problem, because I quite dont understand everything about what was the problem
i don't need you to explain the whole problem. the error was referring to something else and you've fixed it if the error is no longer appearing
It looks like you tried to access a non-static variable called PlayerUI using the class name
when you'd need to tell it which FPSController you wanted to access PlayerUI from
so basically I have a script "client" that handle my websocket connection, and with this script I was trying to call a void in an other script that basically show a certain UI when the player die, and the issues was that my script was using a static class, and the void Died() wasn't static, so it gave me an issue, so I decided to make my "client" script non static, but it was still telling me that I couldn't call the Died() void because it wasn't static, so I tried to make it static and this gave me the error that I've mantionned earlier. then I decided to remove the static atribute from my Died() void and left unity with an error, then when I came back 1hour later, the script compile again for no reason, and the script was fix . (I hope I've explained it well and that my English isn't too bad. ๐ )
If a function is static, you call it with ClassName.Function(). If the function is not static, you have to call it on an instance of that class
I still don't understand the concept of static class and singleton, but now that the problem has been mysteriously solved, I'll be able to take the time to understand these concepts.
it was "mysteriously solved" by you changing something.
#๐ปโcode-beginner message
ok but what stops me from turning id into char no matter how i edit it i cant make it char
It's a string
Strings are many chars
yes im trying make it char instead
i want make string from multiple chars
storing multi digit int in single char is great for coding
Which char do you want from it
i want everything to be char
A string is many chars
yes
even if I'm visibly afflicted with dementia and I managed to fix my bug without even realizing it, I'd like to at least understand what I did to resolve this bug ๐
Thank you very much for taking the time to help me !
Which char do you want from id.ToString("D2")
Because you've made it into a string. A string is not a char
ok so
(char)index + (char)id + (char)rot.x + (char)rot.y + (char)rot.z
why this wont work
why do you need to make it a char here anyway? you're concatenating multiple objects to create a string, why does id need to be cast to char for that?
because for networking i need 3 copies of same var and storing everything in single var is much less code
What does it say when you try
cannot convert int to string
For networking you should be using bytes
this is incredibly fucking cursed. and does not answer the question i actually asked
you are adding multiple chars together which, surprisingly (but only to you), does not concatenate them. it performs an integer addition
ok so adding another () around them should stop it but it doesnt
What type are you trying to store the variable in?
string
You're going to get a char as the result
Char is not string
You'd need to store it in a char
i want mash chars together
Then you wouldn't be adding them
Don't use a string as a ghetto byte[] for networking because you are scared of the data type
what do you think is the result of this operation: 'a' + 'b'
i expected it wont autoconvert them to ints while in char format
ok so solution is starting addition with ""
Solution: Stop doing whatever the fuck you're doing
Have you heard string interpolation
i know i can pack it tighter by storing it as bytes but then it will be pain to reuse into code
@rich adder
Thanks a bunch for the help, I managed to fix what I needed
single char is very nice in every aspect
you're literally going to have to do exactly the same kind of decoding to get it back from the chars
but then it will be pain to reuse into code
not if you do this the sane way
no i can do something like
transform.position = new vector3(string[2], string[3], string[4])
its super simplified
what's going to be even worse is attempting to store a shit load of data in single chars, you cannot fit an entire integer in a char. you cannot fit an entire float in a char. that is not going to work
How is it that every fucking time you post here you're doing some absolutely wild bullshit and refuse to do the sane and simple thing that would solve your problem instantly
This has to be some kind of psy-op
anuked secret ai
Lol what
Can't be. An AI would need to be sourcing its data from somewhere
and literally no one ever at any point in history has ever done shit this wrong
also just casting a float to a char is going to lose data because the char is an integer which means it loses the floating point data and only stores the whole number
ai would also use bytes here ๐
Now they made the history
vector3int i never use floats
you missed the entire point
Anyways int also does not even fit in a char
I'm gonna blow a fucking gasket
"vector3int" except you're using a vector3 right there in the example and if you're storing positions it's not a Vector3Int either
im just saying about solutions that fit are quite more complicated than what im doing mostly
No, they really, truly are not
and theres no arguing that is simplest way to create different data from string
since theres literally no built in method to make vector from string
in that case since you've clearly got this figured out, why are you here?
We call it "deserialization"
yeah i did i only wanted know why cant i add chars
You can
Pretty easily
But what you're doing isn't addition
you're doing what can only be described as a "thought crime"
You seem to be under the assumption that you're literally the only person who has ever needed to transfer a vector over the internet.
This assumption is false.
There are ways to do this. Well-trodden ways with decades of follies behind them.
Converting numbers into chars and packing them into strings to send over the network to unpack into bytes then back into chars then cast back into ints is not it
you can, you just aren't concatenating them, you're adding them numerically into a single char
You can. As numbers. If you want to concatenate them(which is what you want to do from the looks of it", you'll need to convert them to strings first.
dam ppl really want extend discussion as much possible
here i got the solution already
Yes, that's concatenation. They get converted to strings here
This is not "char addition" though
"A" + " " -> "A "
'A' + ' ' -> 'a'
(a.k.a. you are using 8 times as much memory as just storing the fucking vector)
what's the point of this, even
They're scared of arrays
if you were going to stringify this info, you would probably just interpolate the string
if you're trying to serialize it, then.. do that instead of.. whatever this is
Now imagine you have 350 degree rotation
this isn't a solution to anything, wth are you trying to do lol
you must be so deep in a https://xyproblem.info at this point, let's get ya out of that hole
They won't give you the actual problem.
They assume it's "unnecessary"
which is why i gave that link
christ
hi y'all, if I want to transfer data from a sensor to a quest, for a game, how do I set up a connection between the two? I am ultra beginner. I heard from people we have to use a UDP ?
What sensor?
a Lidar that detect pedestrian positions (x,y)
Does that sensor have microcontroller attached to it with a WiFi, bluetooth, usb, RJ45 or other module for networking?
Does it already send the data? How do you configure what it sends and where to?
!code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Im having an issue where my player is constantly gaining y value and floating upward when i move for the first time. Here my movement code https://hastebin.com/share/eneloyobob.csharp
does anyone see anything wrong with it that could be causing this?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Not totally sure why you're floating up... but the fact you are normalizing before zeroing out the y component in both cases is a problem.
Do you have any other scripts, and/or does your gravity happen to be set to a positive y value or something?
How is this code even getting invoked?
Nothing seems to call HandleAllMovement. Presumably you have at least one other script involved.
Why does this not work? If slider.value = 1 then the boolean is true. Does CS not work this way?
= is the assignment operator, not the equality operator
Is it possible to use short-hand notation for this?
there are beginner c# courses pinned in this channel if you don't know how to do basic comparisons
I have not yet configured it, actually I do not have the system yet. I just wanted to get something going on the quest side to be ready to receive data
cs is my second "real" programming lang, i just need to get basics down and then everything else is basically the same.
like i said, there are beginner courses pinned in this channel
This is a script attatched to the player model, when I click down the debug log isn't popping up, anybody know why?
you need to start by configuring your !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
!code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
checking for inequality uses !=
https://paste.ofcode.org/byjkvyva9tuTtmKUSaA4D5 does anybody know why my explosion spawns so far ahead of my enemy when my player colldies with the enemy i tried fixing it by resetting explosion prefab position so i assume its something to do with the code
GameObject exploPrefab = Instantiate(explosionPrefab, transform.position, Quaternion.identity);
it spawns on this object's position
Instantiate(explosionPrefab, transform.position, Quaternion.identity); you need transform of the hit collider
ohh got it thank you both
sorry if it maybe obvious but what would be the syntax of implementing this because i tried playing around with it but all i get is an error
What error?
What did you try?
What was the error?
the syntax is - use the position that you want instead of the position of the obejct this script is on
e.g., maybe you want the position of one of the contacts in the collision: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Collision2D.GetContact.html
oh i tried to do collider.position but i guess that is invalid and doing it completly wrong
Well yeah the Collider2D component doesn't have a "position" property
And why would you want that anyway
you don't want the position of the collider
you want the point where the collision happened presumably
oh ok right now im just researching the contact points and it seems to be what im looking for not too sure as im still kinda new to unity
sorry i meant 2D, would that still work?
You could/should just check the docs yourself
@wintry quarry i struggled for 2 hours just for the solution to be two lines of code thank you
why are my laser beams like this?
using UnityEngine;
using static Enemy;
public class LaserBeam : MonoBehaviour
{
public GameObject player;
public Transform spawnLocation;
public bool isShooting;
public Vector3 spawnRotation = new Vector3(0, 0, 0);
public Vector3 offSet = new Vector3(0, 2, 0);
public float laserSpeed = 100f;
void Start()
{
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
isShooting = true;
}
else
{
isShooting = false;
}
if (isShooting)
{
Clone();
}
}
void Clone()
{
Instantiate(gameObject, player.transform.position + offSet, Quaternion.Euler(spawnRotation));
transform.Translate(Vector3.up * laserSpeed * Time.deltaTime);
if(transform.position.y > 6)
{
Destroy(gameObject);
}
}
void OnTriggerEnter(UnityEngine.Collider other)
{
if (other.CompareTag("Enemy"))
{
// Get the Enemy component from the collided object
Enemy enemy = other.GetComponent<Enemy>();
if (enemy != null) // Ensure the object has an Enemy script
{
enemy.TakeDamage(1); // Call the method on the instance
Destroy(gameObject);
}
}
}
}
this fixed it, thank you
forgot to attach the video
do I have to increase the speed to like 800 it's currently at 100
Please ping me when you reply
you're only calling transform.translate once in clone
this should be put in update
ok so there's several things to take note here
โข this script is on a LaserBeam. If this is attached to the LaserBeam game object, every time you call Clone you're calling it on every laser beam. You're doubling the number of laser beams
โข you should be moving the laser beams in Update. doing it in Clone only moves it once
โข in Clone, you're moving the current laser beam, not the instantiated one
โข in Update, your Input.GetKeyDown code can be simplified to like 2 lines
I would like to ask why the non-null comparison is shown expensive? Then what should I do? >>>
does it do the same if you call .CompareTo
Im trying to get my player to fall on sloped terrain but the issue is they remain floating after they walk off the terrain, and the y level drops by around 0.3 a second. Any ideas? All player scripts: https://hastebin.com/share/wikebeyudu.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
_tip does not seem to have the CompareTo method
The way some games do it is raycasting to the ground if the distance is small enough, teleporting the player there
There's a video on making better player controllers with tricks like these but I need to find it
which editor is this?
if it's anything from jetbrains they have this: https://rider-support.jetbrains.com/hc/en-us/community/posts/12950505395090-About-guide-that-comparison-to-null-is-expensive
Rider
first time seeing this but I don't think it's much of a concern
Ok, I can ignore the tip. ๐
why does unity gray out and not let me edit some options in the inspector?
i add a cube and it doesn't let me change the surface inputs 0.o
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Screen-fullScreen.html
the docs don't specify this, but if Screen.fullScreen is set to on, does that make it "exclusive fullscreen" or "borderless window"? I noticed that sometimes my game "skips" frames and it feels like it runs in slow motion until I set Screen.fullScreen to off, but then it becomes windowed
Just confirming with you guys, are Input.GetAxis("Mouse X") and Input.GetAxis("Mouse Y") framerate independent, thus not needing any multiplication with Time.deltaTime?
Thank you
What would be the best way to get into C# and get enough knowledge about it, so I can start making stuff in Unity? My problem is that almost all the tutorials I found are for people who have no idea about programming, but I have coded in other programming languages before. I have also tried out C# once, but sadly I forgot almost all of it, so I want to refresh my knowledge. There are some more advanced concepts though, I donโt understand yet, like static classes, private and public variables, etc.
I canโt really learn by only reading the documentation :(
I appreciate any advice!
I would still follow the tutorials and just skip the extra babbling
Or look up the documentation, and try to make an application
If you have knowledge of programming, possible ask tiny parts to ChatGPT and try to apply those while learning how the keywords apply relative to what the documentation specifies
It's usually what I'd do
Hey, weren't you the one that told me i gave terrible advice by suggesting chat GPT ? ๐
There's a big difference between telling complete beginners to just let ChatGPT write their code and taking AI code as reference when learning a language as an experienced general programmer
If you have basic knowledge of programming, you can sort of "retro engineering" like i did to learn : import a popular asset renowned for the clean and well commented code, and try to understand how everything works. Join their discord and ask questions about the parts of their tool you don't understand. It's a cool and motivating way to lear for me.
Considering you didn't understand why this was a bad idea to suggest, I really don't feel like having yet another discussion if that's what you're going for
Nope, it was just to kid you, i mean no harm. But still, i never suggested that, just being misunderstood, end of discussion ๐
Beginners take AI code as it is and end up with horrible code and no idea how to debug. There have been plenty of users in this server seeking help with strictly AI code and it is a waste of time
Alrighty ๐
i agree with what fusedqyou is saying, look into tutorials and just skip the stuff obvious to you. For c# specifically, if you have a good idea of programming in other languages you could even try problem solving sites like leetcode or whatever else is ppopular. I wouldnt call "static classes, private and public variables" advanced concepts though, I do question how much experience you have though if public/private specifically is new to you. A lot of languages still have this
As for unity specific stuff, i looked at tutorials just to find out what exists/what its used for. Then id read through the docs and experiment with it in unity
good coders look at code samples and learn from them
asking shartgpt for samples is fine
asking it to generate code just generates headaches
*generate code for you
Personnaly tutorials and doc was a big no to start, but i'm no pro in programming. There is different ways to learn for different people, but i think the worst way to start is having samples by AI because a little bad prompt can lead you to terrible sample, big waste of time at least, big bad habbit to erase at worst.
That actually sounds like a good idea
you could just have chatgpt explain examples instead
still not 100%, but at least there's less oppurtunity for hallucination if you're hellbent on using it
what other languages do you have experience in? we could point to more specific ways if we know what you already know
That also sounds like a good idea haha
That is a good idea, taking samples from the API and questionning AI
(statics and access control are pretty fundamental for OOP for example, but advanced for say, python where OOP itself is somewhat advanced)
Yeah maybe I will just ask ChatGPT to explain me the basic things, and then try to put together some simpler console applications
Just to get the hang of C#
Dart and Python mostly
As i say to my students, take advices, apply them "a little" then choose your way. Sometimes we think this is our way and it works better doing other way (sorry for my english, i hope you get the idea)
ah, i see why you're unfamiliar with OOP then
I wouldn't want to use ChatGPT to write actual code tho, I don't want to take the easy path haha
Ohh maybe I should do that, since I'm not even sure when is OOP used O_o
path of hell, seems easy, then debugging it could turn into nightmare if you rely only on AI ^^
Yes, I got the idea, thank you^^
OOP is object oriented programming. it's a somewhat advanced concept in imperative languages ie js, py, but it's a fundamental in c#, java
and I feel like you have to write most of the code by yourself, because then you will fully understand it and be able to add stuff later
in, i think most non-fp/sh/asm languages, objects are built-in to the language structure, but creating your own classes is somewhat advanced in imperative languages
for example in python, instanceof and class are where OOP happens
Yes, do dirt code and correct it, optimize it. Just do it. But for me a blank script was scary, so i prefered an asset well written and started to read it, and "tinker" it to add small parts, change some things... It was really fun (i do this for fun only, im paid for maths and helping/teaching in non traditonnal ways)
alright, I mean in Dart I pretty much understood classes and have actaulyl used them
The biggest project for now I have in mind is recreating Pong O_o
perfect idea. Flabby birb for physics
oh I guess pong itself does have physics right right
And now combine to flappy pong ๐
I think tetris is best learning game to make since it forces you to learn arrays, and uses the update loop so it's not fully static like checkers
game of life was fun to clone too
arrays and for loops intricated
Hi guys. I have frozen rigidbody constraitrs in X and Y in my unity editor but when I play game, the tick disappears and my player body is able to rotate on X and Y. Why is this happening? I searched online and people are freezing rigidbody in code, but there would be a better way than this...
you sure it's not already being changed in code? Either way, adding it in start is fine too
something in sccript change it for sure, there's no way serialized change instead of this
press ctrl+f and research "Rigidbody.constraints" in VS
Time to make a pong game where you're the ball and you go back and forth between the flipper thingies whilst evading pipes
sound pretty legit
yeah your right there is a rb.freeze n my script. how does one make it freeze on x and y only?
using code
Hi, I have a problem with detection when my hero touch the tile with city in 2D game, anyone can help me? I'm new in coding and i don't know how to do this
We don't know your game, so if you want to be helped you have to give more context
Explain the problem with detection and optionally share related code if it's not related to physics
If it is related to physics, follow these steps, maybe https://unity.huh.how/physics-messages/2d-physics-messages
My hero move by WASD and he "jump" tile by tile, but when he jump on city tile the message isn't send to me. tile with city and my "hero" have BoxColider
and this is a code for my hero to detected the city
private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("City"))
{
// Wyลwietl komunikat w konsoli
Debug.Log("you are in city!");
}
else
{
Debug.Log("it isn't a city!");
}
}
it's look like this:
and the brown tile is city
Does your Unity console show one of the Debug messages?
If box colliders are triggers they wont collide, do you have a rigidbody ?
console did't send any massage
Only at hero
Then please follow the steps from the link. Specifically this step: https://unity.huh.how/physics-messages/trigger-matrix-2d
do you need colliders for this? a better way might be to store an array with information on what's in each cell, that way (for a turn based movement game) you can just read the info on what's in each tile based on the position of your character?
Yeah I don't think collission is really required either, but maybe I am missing something specific
how can i do this?
If he is a beginner, it is indeed better but harder from my point of view
Yes, If they want to learn about triggers and colliders then continue with this way, but if they want a more reliable solution, then storing it in a data structure would make more sense.
let me make an example
Since you seems more advanced than me i have a question for you, i don't really do stuff in 2D but could it be Z axis changes then there is no collisions ?
I personally don't even use Unity
I just know plenty of C#
But collission and things like this are some of the things I do know
- double check if your tag is well spelled
- play your game, click 3D, and see if boxes are actually colliding (if you touch Z axis for graphic parts but didnt make another gameobject for physic part)
been a while since I last did 2d, but iirc this is a thing
So, you're basically my doppleganger, i am unity certificated for game developping but not C# ^^
thats it?
is the box collider a component of this ?
can u explain step by step how to check this? i set 3D vision and i don know whats now
how can i do this?
click on your object city tagged city, if there is a box collider (trigger checked) as a component say yes to me, and tell me if position Z is the same for hero (the gameobject having a box collider trigger and a Rigidby) and city
yes and the position Z is the same like hero
Did you change anything to the physics matrix by layers ? https://docs.unity3d.com/Manual/LayerBasedCollision.html
I only set the layers for hero and every tiles at "3: Tile"