#💻┃code-beginner
1 messages · Page 524 of 1
yes, jpeg is a form of compressed image
yeah that's what happens with lossy compression
the info has to go somewhere, either in the file or in the trash
and you think you'll somehow be able to compress it to less than a thousandth of its original size with no quality lost? 🤔
That is expected if you go from 50mb to 2kb lol
Well I could sacrifice some computation
yeah that's just called heavy compression
but at some point you just can't stuff the data into a smaller space
how big is your image? what format is it in? how big will it be shown?
Raw rgba32 bytes
oh yeah compress that to at least png then
Which are I think as uncompressed texture format might take a lot more space
I wish I could but unity 6 doesn't let me encode to PNG with already compressed images
That's why I am using raw bytes
why do you need to use unity
🤦♂️
Cuz I am making a game
And I want the user to upload the profile pic to the game server
no, why aren't you using an external tool to compress it and then use the result in unity
But due to large size the image is not uploaded

Unity 6 no longer supports encode to with already compressed images
why do you need to reencode anything
ok.
step back
please describe what you're doing
because you're leaving out quite a bit of detail here, this is a case of xyproblem
Let's suppose I let user upload a jpeg or PNG inside the game
Now when I try to get the PNG data of that uploaded image inside unity I used texture.EncodeToPng();
To convert the already running texture into a PNG bytes
it's already a png
you let the user upload a png
what are you trying to convert to a png
But as the image uploaded is already compressed
So unity 6 won't be able to encode it
Nor I can get the simple compressed bytes
I could only get raw bytes
why would you want to
Cuz I am not limiting to upload only pngs
I wish if I could support jpeg,tga,ttf and other formats
In previous unity versions I could
just stick to what unity supports directly, or just let the user convert it themselves
ok, do you support my proprietary bmp derivative that uses uv and ir channels
what i mean is, it's not possible to support everything
good, 20mb is probably an attack. no profile picture needs to be 20mb. it's not going to be displayed at high enough resolution to matter
How much memory would a 512 x 512 image take
very little
An estimate
you honestly dont know how to calculate that?
i just made one and it took 6kb
I just turned 18 a few months ago
I am not that experienced sadly
basic math
Ok I will try this one
i made another one, with much more data. 234kb.
a 4-channel 8-bitdepth bmp (aka uncompressed rgba32) at 512x512 would be 262144 pixels at 4 bytes per pixel, coming out to 1048576 B, or exactly 1 MiB
png and jpg are compressed, so for legit profile pictures that aren't just pure random noise, it'll be much smaller than that
you're really overcomplicating a straightforward task.
have the user upload a pretty small, compressed image, probably just png or jpg, and use that directly.
you don't need to support random formats that a vast majority of people aren't going to care about. if they want to use that image, they can convert it themselves.
if you really want to reduce the size, switch to a 256 colour palette format which will reduce the size by 75%. You could also add RLE compression to that to reduce size even more
this if statement is not being run even though the rotation is above 90 (spine is a Transform). Any help?
is it even being reached? try a debug before it
you are treating a Quaternion as if it was Euler angles
localRotation.y will never be anything outside the range [-1, 1]
how do i check for rotation then?
what are you trying to determine exactly
like "is the player facing east or west"?
bool playerIsFacingEast = Vector3.Angle(player.fransform.forward, Vector3.right) < 90f;```
more generally you can use Vector3.Angle or Vector3.Dot to compare the player'sfacing direction with any known direction
this is more robust than trying to mess around with euler angles.
alright
The details depend on exactly what you're trying to determine
so step one is to make sure you can express that.
im trying to determine if the spine is facing 90 or -90 degrees
that is very vague
what does it mean to be facing 90 or -90 degrees
degrees are not directions
if the y value is 90 or -90
the y value of what
the spine
YOu mean "if the rotation of the object around the global y axis is within so and so a range"
and this is a more robust way to express that
I think you're getting bogged down in the details of euler angles and not thinking about, semantically, what you actually are trying to figure out
what's the end goal here?
like "I want to know if my player is upside down" for example
or "I want to know if my player is facing right or left"
an animation is supposed to play if the player looks too far to the right or left so it doesnt look awkward
so left or right relative to what?
The global axis directions?
or something else
sorry i dont know what that means
"left or right" is very vague
If you're looking south and i'm looking north, left and right mean different things to each of us
in fact they're exactly the opposite
I'm asking you to be very specific about what you actually want here, because you need to be to write the code properly.
how to access the camera targetTexture? unity documentation said i can access it like this but it doesn't work..
Your inability to express your meaning is part of why you are struggling to write the code.
What does your error message say?
Given that StartCoroutine is showing up in IntelliSense, I would guess you wrote your own Camera script (public class Camera) which derives from MonoBehaviour. THat is causing the confusion here.
You would have to either rename your script that you named Camera or declare your field as public UnityEngine.Camera cameraB;
or, third option, using Camera = UnityEngine.Camera; at the top of this file.
I would recommend simply renaming your script though
this one works, thx
do you understand what im trying to do though?
No that's why I keep asking you to clarify your meaning
I vaguely understand but the exact code details depend on your exact meaning
So you should be trying to explain. Maybe show some screenshots or diagrams if that helps.
For example I don't even know the layout/camera view etc of your game
i don't know if it's a top down 2D game or a first person shooter
Or a 3D RTS
it could be anything
I shared a code snippet above that handles the case of a 3D player looking around and the right/left being relative to world space. But without knowing how your game actually works that may or may not actually be helpful for you.
https://youtu.be/v3W2ostR820?si=JWL5DhuVJgGK22Rf&t=722 its exactly this
Hey. In this quick tutorial, I am going to teach you how to create a True First Person Character using Unreal Engine 4. The character will lean properly to follow the players' camera movements, as well as playing proper turn animations.
This works well for First-Person and Third-Person games
Project File: https://drive.google.com/open?id=1GDjhx...
Which part of it
at the point i put in the link
yes
That can happen at any rotation at all
since it's an FPS and you can face any direction
what you care about has nothing to do with the player object's current rotation
you're going down the wrong track entirely
all you need to do is look at the input
I guess mouse horizontal input in this circumstance
to determine if you are rotating the player right or left (clockwise or counterclockwise)
yeah but the torso and legs shouldnt rotate until a certain point is reached
public class Aquarium : MonoBehaviour
{
public static Aquarium Instance;
[SerializeField] private List<FishTank> Fishtanks = new();
[SerializeField] private Dictionary<FishData, int> FishInventory = new Dictionary<FishData, int>();
[SerializeField] float Money = 0f;
private void Awake()
{
if(Instance != null)
{
Destroy(Instance);
}
Instance = this;
}
private void LoadInventoryKeys()
{
}
Hello, I want to know how I could load the dictionary on this class with the keys that would later the player will use to manage the fishes on the aquarium, as buying and placing the fishes on different tanks. Thing is, right now the dictionary uses as key the FishData ScriptableObject. For this purpose I don't know if it would be better to use the prefabs of each fish or just keep it with the FishData.
Unity cannot serialize a Dictionary so trying to serialize that field is not going to do anything.
as for what to use as the key, we don't really have enough information here to make an informed choice
The prefab reference might be a good idea
or if you have a ScriptableObject, that reference would be too
Probably the FishData SO
if that SO has a reference to the prefab
I see. Right now I don't have a reference for the prefab on the SO. I'm trying to load the keys for the player to have a catalog to check the amount of fishes they have. These amounts would be used later on to "pick-up" an X quantity of fish to place them on a fish tank and vice-versa.
what is the prefab exactly
Do you have one prefab per fish
or is there a single Fish prefab that uses the SO reference when being spawned to determine what kind of fish it is
public class FishData : ScriptableObject
{
public enum Type
{
Saltwater,
Freshwater,
Migratory
}
public Type _type;
public string Name;
public int Health;
public float Hunger;
public int Min_Temperature;
public int Max_Temperature;
}
public class Fish : MonoBehaviour
{
[SerializeField] FishData data;
public void UpdateHealth(int value)
{
data.Health += value;
if(data.Health < 0f)
{
data.Health = 0;
}
else if(data.Health > 3)
{
data.Health = 3;
}
}
}
Right now that's what I have referring to the fish object. I was thinking of doing different prefabs for each fish, as, for now, I wasn't expecting to have a lot of them, but, what would you reccomend?
I would recommend having FishData be the source of truth for all fish info.
It should either:
- Have a reference to a specific prefab for each fish
OR - Have references to stuff you need to create a fish like the Mesh or Sprite it uses
and use FishData for your inventory / Aquarium
I see. Thank you so much, I'll check going for the first option.
🥺
hey
public class ThirdPersonMovement : MonoBehaviour
{
public float moveSpeed = 5f;
public float turnSpeed = 700f;
public Camera playerCamera;
private float inputX;
private float inputZ;
private Vector3 moveDirection;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
inputX = Input.GetAxis("Horizontal");
inputZ = Input.GetAxis("Vertical");
moveDirection = (playerCamera.transform.forward * inputZ + playerCamera.transform.right * inputX).normalized;
if (moveDirection.magnitude >= 0.1f)
{
float targetAngle = Mathf.Atan2(moveDirection.x, moveDirection.z) * Mathf.Rad2Deg;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSpeed, 0.1f);
transform.rotation = Quaternion.Euler(0, angle, 0);
}
}
void FixedUpdate()
{
rb.MovePosition(transform.position + moveDirection * moveSpeed * Time.fixedDeltaTime);
}
}
my character can juste rotate
its not normal
you are doing rotation with the transform, use the rigidbody
also don't use transform.eulerAngles as input into any calculation
so I have this issue where if I tilt my camera on the vertical axis too much, my character starts moving backwards instead of how its supposed to move
cameraDirection = mainCamera.transform.rotation * inputVectorRaw;
cameraDirection.y = 0;
if(cameraDirection != Vector3.zero && walking)
targetRotation = Quaternion.LookRotation(cameraDirection) * Quaternion.Euler(0, 45 * offset, 0);```
I think the main reason is that the camera's x axis becomes negative if I tilt the camera vertically below a certain point
but I have no clue how to fix it
i am wanting to create a space game like Kerbal Space Program where you build a rocket and can fly out of planets, orbit etc. I already have the basic rocket physics and building but i am really struggling to get the planets right/have no idea how to do them. how could i make it look like you are on an expansive terrain (unable to see planet curvature) but when you start to fly out of the planet and get higher etc it starts to get smaller and looks like you are exiting the atmosphere
this is pretty tricky to do! Some search terms I'd suggest: LevelOfDetail (LOD), and "chunking".
Hi! I'm making a 2d platformer game where you can enter buildings, but I've realized my player always starts at the default position from the scene editor. How may I go about creating a spawn system that allows the player to show up at the entrance and exit points of the building when coming and going??
thanks! will take a look, my first thought was i could just create a sphere and call it a day but as you could of guessed i found it to be a lot trickier than that!
you usually want code to set the position where the player should appear do that
never used it myself, but I know there is some option to NOT reload objects on scene changes. I suspect you could put the spawn data in such an object, and let it set the player position when the scene loads.
although im not sure its a good idea having something like entering houses be handled by scene managers
usually just teleporting the player is fine
you dont want a loading screen between every house enter probably
I have a fade to black UI to animate transitions no real loading screen
I need to replace ?
Hello! I have a Animated Bird sprite (animated using sprite-sheet) and all I want is for the bird to scroll across the screen. How could I accomplish this?
To correctly move a rigidbody, you need to either use AddForce(), or set it's velocity directly.
Using MovePosition is bypassing the physics engine and forcefully setting the position.
To correctly rotate a rigidbody, you need to use AddTorque, or set the angular velocity.
Keep in mind that sometimes it's OK to incorrectly rotate a rigidbody. Like if you have a snappy first person controller, torque or angular velocity might feel very weird.
what does the animation have to do with it?
im just saying the bird is animated
but i want the bird sprite to scroll across the screen
Ok the fact that it's animated is irrelevant
give it an empty parent object
and put a small script on that parent object to move it across the screen
alright
Anyone have recommendations for an asset from the asset store to handle json files?
I'd like to be able to process the following json into seperate lists, so I'd have a species, prefixes, and prefixes2 list
you don't need an asset for that
Unity's built in JsonUtility would handle that just fine
Any tips on how? Because what i could find about it on google I couldn't find anyway to parse it like that 
[Serializable]
public class MyExampleClass {
public List<string> species;
public List<string> prefixes1;
public List<string> prefixes2;
}
void Start() {
string myJsonText = <however you get your json text. Read it from a file or whatever>;
MyExampleClass ex = JsonUtility.FromJson<MyExampleClass>(myJsonText);
}```
It's a pretty straightforward usage of JsonUtility
Ah gotcha I didn't realize I could use it like that, thank you
I don't think you're wrong I just wasn't thinking about it in the right way 
I think here is my confusion I would like to set the variables of this singleton but I have no clue how to parse it into multiple lists with the way that it works
I obviously can't instance a new singleton.
I guess I could create another class just for it but that feels kinda bloaty and I'd like the lists in my singleton if that makes sense
I ended up deciding on using an interface
Hello, im a noob and im having audio issues
basically i have a little box collider that the player stands on and i have it trigger a sound effect, but im getting 0 sound no matter what I try
the code goes through and adds to the counter on the debug.log, and the audio file is supported, not at a stupid Hz (ive tried 44,100 Hz), and I am honestly just lost
im on unity version 2022.3.13f1 <DX11>
Calling Play repeatedly will cause the clip to constantly restart.
your code is quite confusing to read with the lack of braces and loads of booleans
There's a number of things to go through if the log is only printing once and not repeatedly https://unity.huh.how/audio/silence/muted-audio
sorry about that
Just add a field of a class like in my example to your MonoBehaviour
public MyExampleClass myField;
you wouldn't deserialize directly into the MonoBehaviour
that's not gonna work
tysm for this link
u da goat
:)
Making a bow that shoots a arrow wherever the mouse is, I have the bow rotate towards the mouse as well but the rotate point is on the corner of the bow, how can I switch it to the middle of the bow so it looks better?
Open Sprite Editor in the texture's inspector
Move the blue circle and Save it
That works! Thank you!!!
Its my first c# code, its hard to understand, i need to watch tutorial today, the camera need to just drag and drop on the mesh ?
Hey guys I'm using the new input system to get the axis for vertical and Horizontal inout but the thing is I don't know how to normalize the diagonal movement of my character. I do know how on the legacy input system tho. I'd appreciate the help 😄
private void FixedUpdate()
{
Movement();
Animation();
shootAnimation();
}
void Movement()
{
rb.MovePosition(rb.position + movement * speed * Time.fixedDeltaTime);
}
public void MoveInput(InputAction.CallbackContext context)
{
movement.x = context.ReadValue<Vector2>().x;
movement.y = context.ReadValue<Vector2>().y;
}
The same way? I don't see why it would be any different
oh wait right XD im so dumb
so basically I just had to do it like this
void Movement()
{
movement.Normalize();
rb.MovePosition(rb.position + movement * speed * Time.fixedDeltaTime);
}
fellas i am experimenting with a 3rd person camera on a character controller, and i'm following a tutorial to get it set up. before following the video, i had some very basic movement set up that utilized the input manager's "gravity" and "sensitivity" settings to get the player to smoothly accelerate and decelerate.
when following the tutorial, however, i have lost the acceleration and deceleration, and i'm not sure what part of the code is causing it.
here's a paste of both the tutorial's code and mine: https://paste.ofcode.org/pBRpiCBqqjVjHDJbDdXpnU
i took out part of the tutorial's lines that including normalizing values, as i've learned that can cause the snappier movement that i'm trying to avoid, but that didn't get me where i wanted to be
I mentioned this same thing above with a different person. There's a few issues with your code.
1.) rb.MovePosition is not how you move a rigidbody in a simulation correctly. You should be using AddForce or setting the Velocity. If you use rb.MovePosition, you are bypassing the physics engine. Your character will do weird things like teleport through objects.
2.) Time.fixedDeltaTime isn't really needed in FixedUpdate. FixedUpdate is already framerate independent.
It is needed for MovePosition (but not for AddForce or setting velocity)
Why though? 🙂
Because MovePosition sets the position directly. So if you change the fixed update step or timescale, it'll start moving at a different speed.
Is there a way to include a double jump on my Input System Controls?
I'm unsure if it should be in PlayaCharacterNormalLocomotionInput(Since it has my OnJump function) or PlayaCharacterNormalController(Since its where most of the character movement takes place in)?
how do I make a menu stay on the center of the screen?
How could i start learning this engine ?
Should I ask a animation coding question in here or #🏃┃animation?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
If it relates to code, you post it here with the !code. If it's purely animations, post in #🏃┃animation
📃 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.
am i insane or should this be returning a boolean, not just it's own type?
playerTargetHit is cast as a raycasthit2d, i just didn't want to send a third image for one line
according to the docs, it returns a RaycastHit2D object that can be implicitly converted as bool to check whether the result is valid or not
What do the docs say?
that means you can simply assign that result to a bool variable or use in inside an if statement
ah
implicitly converted, okay
i figured this meant it was just always returning a boolean, bit silly of me since it does say above it returns an object
thank you!
Lol
Classic Unity
Implicit conversions
Why not just add a field/property
speeds it up if you know how it works i suppose
but yeah it sucks if you're figuring it out
not sure why this API is different from Physics.Raycast with the out paramter
Yeah it would help beginners because implicit cnversions is the most unclear thing in the world
Especially here it doesn't even make sense. It's just some weird convenience
yeah </3 most of my experience is with 3D so far
Exactly, this is the best way
Would be nice if they called it TryRaycast but at least it uses the proper convention for a predicate like this
I don't think that would be any more clear name though. Whether or no the ray hits something, a ray is casted regardless to look for hits, at least I think of it tthat way
It would be more clear because by convention .NET methods that begin with Try always return a boolean indicating success
And if they return false then it should be assumed that you can't use any of the out parameters
I guess
And in the case of Physics.Raycast it appears that out RaycastHit hitInfo will be null or at least its default value if the method returns false
In modern .NET you'd also make sure to annotate your out method with [NotNullWhen] or [MaybeNullWhen] to better help with nullabillity. In the case of Unity this also works, but nullabillity is still completely optional until they update their codebase
Useful to know; this type of pattern also exists for AsFoo() to indicate a method casts to a different type, and ToFoo() to indicate the method allocates a new object in order to return the type.
I agree with Aleksi, Raycast doesn't "try" to raycast, it always does perform a raycast
It would only make sense if it would be called TryGetRaycastHit
this server is for helping you make your own thing, not to make stuff for you
if you're just looking for examples or whatever, try google
if you're having issues with your own implementation, ask about those issues
I only use C# with unity, is this what you are talking about?
https://learn.microsoft.com/en-us/dotnet/csharp/nullable-references
And do you think that will fit into unity workflow if they update to that version?
enemy script not working
i did but enemy is not dying
even animator also not working properly
and type in full sentences
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class enemydie : MonoBehaviour
{
public int HP = 100;
public void TakeDamage(int damageAmount)
{
HP -= damageAmount;
if (HP < 0)
{
// play death anime
animator.SetTrigger("die");
}
else
{
//play get hit anime
animator.SetTrigger("damage");
}
}
anything wrong in my code ?
enemy is coming to me
i shoot
but enemy not disappearing , enemy is capsule
i don't see any code for dissappearing the enemy, just setting a trigger
!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.
but yeah you didn't tell it to disappear, so why would it disappear
So do that
!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.
still not working
..did you change anything?
"not working" doesn't give us any information
we can't help you if we don't actually know what the problem is and how you're trying to solve it
In this code, how do you think TakeDamage(int damageamount) is being called ?
no, that's not a problem. that's just the situation you're in
@honest sedge Don't cross-post. You were pointed to the channel where to post
Yes, you're right. Technically it raycasts. The main point of the method is to retrieve something using a raycast, so it would be more sensible to rename it
Yes, and nullabillity in general where your variable context would indicate if it could be null rather than not specifying it
Wouldn't that like break all existing code?
Note in current Unity you can enable it in the csproj file: https://learn.microsoft.com/en-us/dotnet/csharp/tutorials/nullable-reference-types#create-the-application-and-enable-nullable-reference-types
You can also use the nullable pragma:
#nullable ENABLE
private string? _nullableString;
#nullable DISABLE
You can put this at the top of your files without the disable to enable it over the whole file
I think in the case of Unity the compiler is undecisive and just assumes everything can be null
(the mask goes in the brackets, the link goes in the parens.)
I am about 99% sure that if Unity were to release the .NET update they have been working on, they would fix all this
So it's somewhat useless there, but it would work good with your own code
Yes, I have that. It doesn't like my link apparently
lol it does take a while to remember the order. i struggled a quite a bit with the order of brackets/parens lol
Regardless, obviously this all doesn't apply with the raycast here. Though I do think it would point out the possible null reference with RayCastInfo (unless it's a struct, is it?)
Unity would have to use the [NotNullWhen] attribute to fix it.
You mean raycasthit? It's a struct yes
you mean RaycastHit?
In 2D it has a implicit bool cast so you can do if(hit) tho
you can also select the words and paste the link on top of them, most markdown editors support this
umm guys can i ask about how to let vscode underline my errors?
instructions ⏬
if(Input.GetKeyDown(KeyCode.Space) && Time.time > _canFire)
{
FireLaser();
}
void FireLaser()
{
_canFire = Time.time + _fireRate;
Instantiate(_LaserPrefab, transform.position + new Vector3(0, 0.8f ,0), quaternion.identity);
}
}
no errors or anything but for some reason the cooldown system isnt working, i couldnt understand why
you def have errors
if thats truly your code as is
you might want to configure your IDE
Please configure your !ide because this code will not compile
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
When you've done that your editor will inform you of the issue.
it already underlines errors though
show that it is underlining then because this most certainly would
it doesnt
i just wrote what was shown in a course
this is what yall mean by underlining right
well you are using the quaternion from another namespace then
probably UnityEngine.Mathematics
it should still work though
they have implicit conversion
just from what I see here, I think your issue is that canFire never starts as true
assuming the code is actually running at all which you still haven't verified
wait canFire is not even a bool ?
naming confusion is confusing
why is a float named canFire
and did you put this script on a gameobject?
This is incorrect
Your editor seems to be able to highlight C# specific semanthics and symbols
But it doesn't even know if it exists
So no, it's not configured
yes
its configured
So configure it first, then come back
Hover over quaternion, and tell me what it says
they just pulled the wrong namespace for Quaternion
its from mathematics namespace but works just fine
yeah
that aint the issue, the function is probably not even being called.
Fair
its in the unity API aswell
In this case I suggest you log if your if statement is entered at all
yeah put some logs and check what is actually happening
And then also log if the Awake of whatever _LaserPrefab is is being called, in one of its scripts
alrighty
Important thing is pinpointing what specifically doesn't work
no unity calls it nextFire which makes more sense
https://docs.unity3d.com/ScriptReference/Time-time.html
canFire implies a bool at first glance, if your variables dont exactly describe what is at first glance its not a good name
whoops i read it wrong
the instructor in the course wrote it as canFire
probably bad course
good variable names should be most important
anyway check the logs, see whats going on in the code
its an official authorized course tho
the learn.unity site?
this thingy
ah yes. Udemy trash
it logs it when i press space
so its working, just not as intended
where exactly did you put this script ?
just these
No i mean which gameObject
cause transform.position is relevant
you can verify it spawned something just by pausing the game after pressing space, check the hierarchy for new object
So then it instantiates
What object is this script on?
its in the blue cube, its supposed to be able to shoot a laser whenever i press space (with a cooldown of 0.5 sec)
im trying to make one of those galaxy shooter games
show the pivot of this gameobject and inspector
Please get the return value of Instantiate and use it as the second parameter in Debug.Log, like this:
Debug.Log("Object: ", spawnedObject);
Then click the log message
I assume your cooldown system works then right?
It's just that the game object doesn't appear
So if you do this we can verify if the spawned gameobject is actually there still
instantiate and everything else works but just the 0.5 cooldown doesnt work
Then please log _fireRate
That would be the only thing left
Or does it log each time?
ok but i meant the blue cube because wantedto see the inspector values
I'm a bit confused by your message
im quite confused aswell
im halfway of a beginner, i dont really know how to log _firerate
my bad
so it shoots once and stops shooting or it keeps shooting fast on every tap ?
because 0.15 is pretty small amount of time
Debug.Log(_fireRate)
firerate (cooldown) doesnt work, i can spawn as many objects as possible depending on how quick i press the space button
are you pressing faster than 0.15 seconds
make the firerate longer like 1 sec
and check its actually doing anything
oh fuck
fuck
fuck my brain
everything works fine
i thought the cooldown was 0.50
my bad
it works correctly i just forgot that its 0.15 and not 0.50
always check the inspector values if you have them also in code
thank you both for the help
inspector always overrides anything you initialize with
i have been trying from 2 days continuosly but still i unable to code enemy , when enemy got attacked by bullet in unity he doesn't disappear , can anyone help me ? unity pros
you need to show use some !code and to debug
📃 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.
start with showing the code n setup
if i hit enemy with bullet the capusle should disappear
i don't know how to use
read it
read it
open bin site link, paste the code, save , send the generated link
!screenshots
No
Be mindful, if someone requests your code as text, don't send a screenshot!
yo
i pasted code in pasteofcode.org
you would use the collision.transform.gameobject to destroy the gameobject it just hit
so hit save and send the link
link ?
so you not know what a link is?
yooo
yea
what is your question
so send the link
anyway you should debug and go through this guide
https://unity.huh.how/physics-messages
my question:-
normal c# different than unity c#?????
c# is c#
C# is C#, it just uses unitys api
unity is just an API that uses c#
lol
lol thanks
did you got it ?
yes
wait also
this link u mean ?
i am new to this things
yes thats only one script, anyway nothing is wrong in the script itself it seems
did you click the link I sent?
likee ahh 4
yes if you learn C# you will understand C#
go through the wizard https://unity.huh.how/physics-messages @orchid bridge
if you learn unitys API you will understand the API
yea but what's all this ? looking so classified
read it
its a guide to troubleshoot collision messages, click each step
so... i will have learn normal c# and then i will be able to become a good codder in unity
if you understand C# and unitys API you will be fine
ooh
also one more questino
do y'all sort your scripts into folders?
if you learn C# you will be able to read most of any API including unity
unity does not compile after i save the file in vs studio
ohhh thunksx
depends on the project
you have an error probably
why there is no voice channel or some screen sharing type , so i can tell my problems easily
i tried fiing it didnt work
i mean i have a pretty small project, just a lil horror game
some project Assets/MyFeature/Scripts
or some Assets/Scripts/Enemy
Its up to you really
configure your IDE if your IDE does not tell you where it is
!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
what is IDE?
so if only me is doing the game then don't sort em and put them all in one folder?
integrated development environment, aka the text editor that knows what code is
start here
https://learn.unity.com/learn/pathway/unity-essentials
i will guide you through it
Integrated development environment, it helps you code
But it is not a text editor
also make it a habit to google things you don't know @twilit rivet
if you have a lot of scripts that you can categorize you probably should
good organization isn't just for other people, it's for your future self
You're the one thats going to be working on it, figure out what works best for you
if you're with a team, agree on a specific structure. Trial and error, what works best for you
sir yes sir!
lol yes researching things / googling will be 70% of your development
:> what about chatgpt?
stay away
you will be copying things you won't understand and that won't help you gain skills
true fr
can anyone send me code ?
so not use chatgpt for it
what code mate? you have to learn to debug when things dont work as expceted
correct
thanks guys
you wont learn anything frankly
byee:>
anyway you need to use the collision.transform in the OnCollisionEnter, also why are you using Vector3.Movetowards in Moveposition?
you guys didn't understand my problem
You said nothing is happening when bullet collides, its not destroying
well what is it? I thought you said your bullet is not destroying the enemy
so is the bullet destrying itself ?
bullet is sphere , they move forward , if they hit or pass through a enemy capsule (code) it should disappear
if so then you just need to add one more Destroy method for enemy
yea
and use the collision.transform
.gameObject
you cant destroy transform can you ?
destroy methods
game objects also not working
yes I know I was just telling them how to get the transform
ohh alr
thats why I said to debug the collision..
I said it here #💻┃code-beginner message but they ignored it
how to debug ?
putting logs..
you know if you followed the steps to what I linked it would tell you this.
ok i got it
is there any vc channel here
no
navarone and I already gave you your answer above
here #💻┃code-beginner message and here #💻┃code-beginner message
your question is not very complex, doesn't warrant a voice chat
also I suggest you learn here as well #💻┃unity-talk message
anyawy you should not be using MovePosition to move your bullet. Just set its velocity (and make sure it's not kinematic)
likewise it should not be rotated via the Transform
only via the Rigidbody
atleast i need some hints
you have been given many
MovePosition is the enemy script i think
if anyone like to help me , they can dm me
the enemy should also not move via MovePosition and should not rotate via the Transform
why are you just ignoring our messages?
for rigidbody you would use LinearVelocity, Addforce, or moveposition (as long as it is kinematic), NO translation as that causes unreliable collisions
if you truly want help, LISTEN/READ whats being said to you
from 2 days i didn't sleep well , unable to think
What even is the question, I was trying to follow the reply chain but the trail went cold
Their bullet is not destroying the enemy when hit
bullets going through capsule and capsule are still alive , they should be dead and disappear , shouldn't be visiblle
How are you detecting the collision
does the bullet even have a collider
go to sleep
Yeah probably this
3 correct answers have just been said, but also we gave you your answer already
your bullet should have a collider and a rigidbody as well (since you are using addforce)
being tired you won't be able to follow our help, it will appear more confusing than what it is. A well rested mind goes a long way in development
so understood now why NVIDIA CEO told in future there will be no need of coding
coding is like 
only when tired and when you do not understand it
Everything you're not experienced at seems like 
it is if you dont understand the basic principles
Pole vaulting is like 
actually the thing is i have project , i mean record work , i need to finish and upload it
go sleep
get some proper rest, come back to it. You will be able to better approach the problem
and you will have a fresh mind when woken up
We don't say it for fun, its from experience
hello so I have a healthbar like the first image for my game but when I run the script the healthbar turns black like the background I have in 1st and on 2nd is the green health using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HPBar : MonoBehaviour
{
[SerializeField] GameObject health;
public void SetHP(float hpNormalized)
{
// hpNormalized should be between 0 and 1
health.transform.localScale = new Vector3(hpNormalized, 1f);
}
}
this is the script pls help
sounds like it's being set to 0 and just showing the background
you should look into using a filled image for the health bar instead of modifying the scale of the object. much cleaner, and will look much better too
filled image like in?
as in an image component set to the Filled type
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HPBar : MonoBehaviour
{
[SerializeField] GameObject health;
public void Start()
{
health.transform.localScale = new Vector3(0.5f, 1f);
}
}
btw I also tried this
please share !code properly 👇
📃 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.
backticks are to the left of the 1 key on most keyboards.
Just copy and paste it
or you can copy them from the embed if you can't find yours
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HPBar : MonoBehaviour
{
[SerializeField] GameObject health;
public void Start()
{
health.transform.localScale = new Vector3(0.5f, 1f);
}
}
no its just for the testing as the gameobject health
that doesn't make anything clearer
like basically I have a gameobject with an image component with just a custom color
Please help me on #archived-code-general
Then use fill amount, not scale
please don't crosspost
wait I will show what I mean
1- don't cross post pointing people to another channel (against the rules)
2- your question doesn't make sense.. go back to that channel and edit the message to make your question clearer.
Ok, and sorry again for cross posting.
basically I want to achieve this
Filled. Image.
Like we've said a ton of times
I linked you the property to use
but wouldn't I have to do it for all states of the hp?
what
go to your image. select the image type filled
play around with it
see how it behaves
like if I want to show it reducing I will have to do it for every time the hp decreases right
but it is not an image it just has custom color assigned to it
So, you want a system where you can input a percentage and the health bar just instantly goes to that percentage of the way through the bar then?
please. stop arguing
go try it
you said it was an image component, right?
but you don't understand! they want exactly what the filled image does!
but if I don't have an image how do I apply fill?
this is code-beginner
that's a message link
i linked to a specific message
ok thank you for helping me everyone hope you have a good day/night
Open paint. Click paint bucket, click white, click canvas, save. Done use that
there's built-in assets for that
you don't even need to do that
I know but this was easier than explaining how to find them
wdym it's literally clicking the "hidden" button and typing "square"
Yeah but you've seen how this exchange has been going
fair
Hello. One question, for the Color variable type, the red value from what value to what value does it have to be please?
like is it from 0 to 1 or from 0 to 256?
i would check the unity !docs for the Color type. the answer lies there . . .
okay thanks
hey ive got 2 questions regarding my code. 1: Why isnt the cooldown working properly? it makes you unable to move when u try spam clicking (im guessing its performing the routine so many times that it overlaps) 2. How can i make it able to read only one input at once?
heres the code:
Fix the coroutine
my guess is the coroutine . . .
Store it in a variable
you should store it in a coroutine variable. that way you can check if it's null (which means it's already running) . . .
yeah, what they said . . .
would that also fix the second issue?
not sure why you wait for .01 secs.. just yield a frame . . .
let me specify. the issue is that if you press A and W at the same time it throws you at a random point somewhere in the middle (form 0 to 1.333 for eg.)
and i dont want the player to move on the diagonal
you start the coroutine in two different places:
-
Update
whenMovementis performed andCooldownOnisfalse -
Move
if you can move,Cooldownis called, but you're not calling it as a coroutine. Did you mean for this?
In Move you're not starting the coroutine properly
You must use StartCoroutine to start a coroutine
i must have missed that
since i called it wrongly in the first place and fixed it just now
also your movement is just accepting ctx.ReadValue<Vector2>() as the parameter
if you have a joystick that can be diagonal
when the movement is performed, i would check that only one axes is pressed . . .
you should process that vector to make sure it's only going horizontal or vertical
☝️ exactly this . . .
yeah its exactly what i asked about
i mean.. write some simple code
a few if statements
check which axis has a larger absolute value for example
you have all the information needed (the ReadValue<Vector2>()) . . .
Vector2 ManhattanizeInput(Vector2 input) {
float horizontal = input.x;
float vertical = input.y;
Vector2 output;
if (Mathf.Abs(horizontal) > Mathf.Abs(vertical)) {
output = new(Mathf.Sign(horizontal), 0);
}
else {
output = new(0, Mathf.Sign(vertical));
}
return output;
}```
Something like this?
yeah that would work
there's probably also a built-in processor in the input system. I think "digital" or whatever does it
how does OnDestroy actually work? Will unity wait to destroy the object until everything in OnDestroy is finished?
you can check the unity !docs for how it works . . .
Well, since only one line of code can be run at a time, there's no "waiting" involved. The function is called and will run to completion, like all other functions
If you're asking whether it's called before or after the actual destruction, it'd be before
ok that makes sense thank you
does anyone know a better approach for this? this doesn't seem very efficient + throws errors when leaving playmode
essentially i want any attached SoundObject objects to be put back into the pool before the parent is destroyed (in this case the SoundObject is used to play a grunt on a person, but if that person is destroyed i want the SoundObject back in the pool)
{
public PlayerInputActions playerControls;
public InputActionReference interact;
private bool isInteracting = false;
private bool isPlayerInRange = false;
protected override void OnCollided(GameObject collidedObject)
{
if (collidedObject.name == "Player" && isInteracting)
{
OnInteract();
isInteracting = false;
}
}
protected override void Update()
{
base.Update();
Debug.Log("isInteracting is " + isInteracting);
}
protected void OnEnable()
{
interact.action.performed += PerformInteract;
}
protected void OnDisable()
{
interact.action.performed -= PerformInteract;
}
protected void PerformInteract(InputAction.CallbackContext context)
{
if (isPlayerInRange)
{
isInteracting = context.performed;
}
}
protected virtual void OnInteract()
{
Debug.Log("OnInteract() is executed.");
}
// Detect when the player enters the trigger area
private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
isPlayerInRange = true;
}
}
// Detect when the player leaves the trigger area
private void OnTriggerExit2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
isPlayerInRange = false;
isInteracting = false; // Reset interaction when the player leaves
}
}
}```
am i just trippin or is there any better way to handle this kind of interaction system
Which error are you getting ?
the 2nd one is from calling OnDestroy
i think both are actually
probably because you're returning objects to a pool (that gets destroyed along the scene) when you exit playmode . . .
Maybe try the event thing like I do
yeah, try to use events instead. that should work . . .
Basically my child object that I parent to this, listen to event invoked by this object when you call Destroy on it
im so confused tho, how is this different from OnDestroy if it happens before the object is destroyed?
the object is marked for destroy you probably dont want to try to access the transform while its destroying
... i thought it doesn't start destroying until everything in OnDestroy is finished though? is that not the case?
maybe i misunderstood earlier
once you call Destroy the object is marked for cleanup for the GC , once the GC comes to collect the object is cleaned but if you did a null check the object would probably show nul
wait i just realised - if its already "marked" because its parent is being destroyed, is there no way to save it?
because that was the idea with my approach
ah okay
that makes more sense
hey guys, can someone help me? a friend of mine is coding a game, and has found this bug, where the [SerializeField]; GameObject and Interactable is not getting the green color (idk how to name it LMAO), he asked for my help, but i've never seen something like this happening with me, any ideas of what is causing this to happend?
Your friend needs to configure his IDE
!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
(IDE means the program he is using to write code - in this case, Visual Studio)
Is there a way for me to reference one script inside of another? Ie script 1: Potatofarm.cs, has the "createpotato()" method, script 2: farmmanager.cs, calls "potatofarm.createpotato()". Specifically i also want to change a variable in potatofarm, in farmmanager.
Yo i need help with my unity game, its a school project and its due in an hour can someone please help me <@&502884371011731486>
Don't ping moderators for non-moderation reasons.
then who do i ping?
aight
: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 #854851968446365696
working on ML-Agents Hummingbirds tutorial. These errors came, but I don't think they should exist
the reason I don't think they should exist is cause i was really frustrated by following the tutorial and it still giving errors so I copy and pasted the source code
and it still gave errors, the ones I put above
only happens when it says "public override void" like here
so I tried removing the "override" from it, and then there were no more errors. But then when I saw my scene there was nothing in it and I do not know why
Help would be extremely appreciated. I don't know how much people care for ML-Agents these days but this is for school so it's rather urgent
Hi! I'm having issue configuring UnityYAMLMerge with Unity and Rider. Could you please give me some advice how to do it properly?
It looks like it should work OOTB, but it's looks like it's not. Have a lot of conflicts in scene. Check this ticket https://youtrack.jetbrains.com/issue/RIDER-33411/UnityYAMLMerge-Smart-Merge-support but still not working for me.
Yes... These are basic things in Unity programming. You should follow !learn to learn the basics.
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
uh, i appreciate it, but im kinda looking for either what this is called or how you do it, i can't really look through the whole unity learn docs to do this
You rather add up getting stuck instead of going through the basics once to understand unity and c#. I am sure, people will get tired here, if you come back again and again for the same level of knowledge and stop helping.
imma be real i already know the basics, i haven't used unity in a while and i just wanted to be reminded how to do this cause i didn't remember, and a quick google wasn't giving me what i want.
But honestly? It's the beginner channel? For beginners? Even if i literally just opened up the software literally just answer my question its not hard? Watch this:
"Yeah you reference scripts like they're types:
public helperscript h = new HelperScript();
h.fun();
But you should probably learn the basics first <link>"
I can't seem to get 3d animatons working, I'm using a lowpoly character model from unity asset store and mixamo animations. Anyone able to assist?
probably talk about the exact issue you're having, are you making the animations and then they're not working, do you not know how to make the animations, what have you done and what exactly isn't working
I've set everything up according to a unity discussion post that was made, the animation in the animator tab is "running" but the animation in game scene isn't showing up.
if it isn't related to code you should probably post this over #🏃┃animation
otherwise show us the code that's causing the issue
Hey, I am getting this really weird issue where my code is just not executing after a certain point even tho I see virtually no reason for that to happen o_0
Like there are no if checks, no asserts, no breaks, no returns, no errors, no nothing, and it just doesn't execute, therefore causing my program to not function properly.
Could somebody help me with this?
This is the chunk of code:
/// Loads config values into a new Config object
private void LoadConfig()
{
const string debugPrefix = "LoadConfig: ";
// Reset to default to make sure all vars are set and changes no longer present in config are undone
// Using ResetSilent because the OnChanged event will get triggered by Load() anyways
Config.ResetSilent();
Debug.Log(debugPrefix + "Reset to default config");
// Reload the config
JsonUtility.FromJsonOverwrite(_configText, Config);
Config.Load();
Debug.Log(debugPrefix + $"Loaded config from {_configPath}");
}
It all gets executed, right up to the Config.Load() method, where it abruptly stops, and I get to output whatsoever, it can be seen in the picture I provided where I get the Debug before the json thing and then no output afterwards.
I know it's after the json thing it stops because I had additional debug logs, and the ones right after the json thing printed.
Here is that same chunk of code in my github repo so you can get a wider context of the code, it's a bit messy but shouldn't be the worst code you've seen:
https://github.com/nnra6864/Nisualizer/blob/e95df38c38ad80ab7998ff225d118b47dce70b01/Nisualizer/Assets/Scripts/Config/ConfigScript.cs#L88
If you mean, am i sure that Unity reloaded scripts etc., yes, this is not the first save
I suggest you use Newtonsoft instead of JsonUtility. Would not be surprised if it just hangs for no reason
Not only once did I have the issue, that the IDE and unity got out of sync. Close it and open it from unity again and see if its up to date
from my understanding, instead of creating a whole new object, it overwrites values in the current one, and that works from what I can tell
Maybe put a log past FromJsonOverwrite to see if it's either that or the config loading
I should mention that this is also not the first time I got some weird singleton behaviour where it straight up reported that I was creating stuff in OnDestroy, even tho I never did that, but it also caused singleton to not be present in the next play etc., here's a link to my singleton too:
https://github.com/nnra6864/Nisualizer/blob/master/Nisualizer/Assets/Scripts/Core/GameManager.cs
I did, as I said in my original message, let me restart the editor as twentacle suggested and put an additional log once again, just to make sure
Right
If I were you I'd ditch JSONUtility in general even if it doesn't end up being the issue. The tool is very bad
This is some weird code. Its a monobehaviour (so already present on a gameobject) but still checkin if its null and if so, create a new gameobject but never add but get the component on it. Does this even work?
nope, that wasn't it, same issue
let me try the other log
yep, I do get there, several times in fact, not a single time does it call the Config.Load() thing
quite possibly, it's been a while since I wrote that, let me check it rq
I see, I wasn't exactly sure what tool you recommended back in #archived-code-general, would you mind clearing that up?
Newtonsoft Json was recommended. the usual json utility is quite limited to what it can do. good for simple task but can fail quite easily when it gets a little more complex or deeper in hierarchy and what not.
Ok, I just went through the GameManager code, what's wrong with it?
I see, I'll look into that
I do not get the Instance get setter values. You are checking if its null. And if it is, you create a whole new gameobject without any component but trying to get it. I guess, it never gets to that part of code, but it just looks wrong, because your gamemanager is a monobehaviour and should be on a gameobject anyways already
Ah, I see your point, I'll refactor that to my newer standards.
I used to write game managers that could be instantiated directly from the script, which means that I'd first check if it's not set, try to get it from the scene, if I couldn't find it in the scene create a new one and then return that.
I don't need that in this project and it's a good point to remove it, thanks.
I also created like a singleton base class for myself to easily reduce the code of all those instances doubled in all scripts, just a tip 🙂
oh, I never make script singletons if that makes sense, if that's what you are on about in the first place
I always have a game manager that has all the singletons on that, or a scene manager if more appropriate
but yeah, what you suggested is actually an excellent thing, it fixed the bug of some things being called twice, however, it didn't help the actual issue I reported :/
I also discovered that I do get past the Config.Load() function and this is where it dies instead:
https://github.com/nnra6864/Nisualizer/blob/e95df38c38ad80ab7998ff225d118b47dce70b01/Nisualizer/Assets/Scripts/Config/Config.cs#L17
Anyways, I'll stop spamming now and actually try to debug now that I have a slightly better env, thanks.
Yeh, was just one thing to easily fix and therefore not run into null errors because of double subscriptino on delegates or what not 🙂
feel free to come back with more insights, interesting topic still
yeah, I'll try debugging with rider now, hopefully I get to something
because the thing that stops the execution is rather simple, I genuinely don't see why it'd fail :/
public static Texture2D TexFromFile(string path)
{
// Replace the relative with absolute path
path = path.Replace("~", Environment.GetFolderPath(Environment.SpecialFolder.Personal));
// If the image file doesn't exist, return null
if (!File.Exists(path)) return null;
// Read image data and store it into a Texture2D
var data = File.ReadAllBytes(path);
Texture2D tex = new(0, 0);
return !tex.LoadImage(data) ? null : tex;
}
public static Sprite Texture2DToSprite(Texture2D texture) =>
texture == null ? null : Sprite.Create(texture, new(0, 0, texture.width, texture.height), Vector2.one * 0.5f);
public static Sprite SpriteFromFile(string path) => Texture2DToSprite(TexFromFile(path));
you could try a try catch block to get the exception
there are no exceptions, that'd be too easy
I did figure som new out, it ain't even that piece of the code
There seem to be a bunch of unknown parts here 😄 at least it feels like it reading along.
It's this actually: Live Config Reloading 😭
For some reason, when I save the file(at least with neovim), it triggers both the changed and renamed event.
Why? Yeah, I wish I could tell you tbh.
But anyways, I enabled debugging w rider and found that it jumps across code like crazy, it literally starts executing the chunk of the code I sent previously, then jumps back to where the event gets triggered, then there is a race condition between 2 TexFromFile() and I think my head hurts.
So for now, imma try to unsubscribe from the rename event
Does it say miscellaneous file on the top left in Vs code? If so it happened to me once. In my situation the intelli sense wasn't working properly so I made a new project moved everything there and it was fixed.
Maybe its firing the event in case you change the content or what not. But yeh, seems like your events are not listening carefully for the changes. You might need to unsubscribe while doing other stuff to the file.
decent idea, sad to report that wasn't it either :/
I think I'll just randomly solve this one after 2 hours of trying random stuff
will let you know what it was once I figure it out, thanks for dedicating your time to helping me
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
i was working on my player movements and one of the abilities i.e. "Dash" was working fine before now suddenly it's not, help appreciated
https://hastebin.com/share/remafirimu.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
maybe your isAttacking flag isn't being set to false?
private void Dashability()
{
if (dashCooldownTimer < 0 && isAttacking)
{
dashCooldownTimer = dashCooldown;
dashTime = dashDuration;
}
}
are you supposed to dash when isAttacking is true?
nope?
no attack1,2,3 when dashing or moving
if (dashCooldownTimer < 0 && isAttacking)
this line makes sure you can only dash if your attack animation is going
Hi, is Unity 6 is LTS version, and recommended to use ?
BEFORE .. you want it to be !isAttacking
or isAttacking == false
man i want no movement except jump when im using dash
no attack
or any combo
dash is working somehow now, but i can still attack while dashing
if (!dashing) { attack; }
im making flappy bird by tutorial and now im trying to fix so that whenever the bird dies it cant earn points by going trough the pipes but a script can't seem to recognize the public bird dead bool
because the class with the error doesn't have a bool called birdisalive. It needs a reference to the other class, and then do bird.birdisalive
Choose the best way to reference other variables.
so private bool birdisalive?
how do i make random integer in a range
no, how did you jump to that conclusion from what I said?
throw a 'unity' in front of this and google the exact message
like in middle pipe but just give me a min il read the link
i did tjis but it says error or random.range
it does not say that at all
not the single line.. the entire screen
y does it do that
but maybe read the error
the error tells you why, hover your mouse over the red squiggly line..
our cdn may be blocked in china
what has that got to do with coding?
Hi dudes, how can I make up and down idle animation into an object?
hello every one when i take an object x and y positions will it store as int or float values?
Float
Well, the positions are in Vector3 which are comprised of floats. Whether you choose to take the individual values as floats or ints is up to you.
what is the benefits of using vector3 ?
It can represent a point and direction?
Is the transform.position includes the rotation too?
transform.rotation
ok i give up
no, u cant
ok i take break 👍
I didn't link you the whole Unity docs, I linked you learning tutorials
- Use
Awakefor assignments and preparations, notStart.Startis to invoke actual logic. - Do not use
Findtype methods likeFindGameObjectWithTag. Use proper references. For example, with a singleton.
ok i did the awake thing il try to research the singleton thing now
you have to access the boolean through another declaration like the script you just declared here Public LogicScript Logic;, so you must access it like so Birdscript.birdisalive
hello, im making a collision system with raycasts. Here is my code : https://pastebin.com/ZHSRG6uD
the problem is that when my down collider hits an arrow. I get this error :
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.
and my tickManager : https://pastebin.com/AW5bPggJ
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.
Is line 79 there similar to the posted code
SetDirection(_Hit.collider.gameObject.transform.forward);```
Well, something is null, so in this case you've a bunch of dot operations going on. If you want to just log it out, then start from left to right.
what does left to right mean ?
hit collider is null
I was thinking hit is null, but they do a comparison earlier and it didn't seem to throw an error
hit cannot be null it is a struct
yes it works for other colliders
OnHover is called every frame in Update if i look at a card, however i want it to only be called once so the Animation does not play every frame. Ive set a hover boolean to prevent this but it doesnt seem to work. What did i do wrong?
so i dont get the eror
They overwrite the _Hit variable on line 74
ohh i maybe need another raycast ?
If all that raycast does is check if it hits anything you don't need a variable at all
it fixed the issue thank you !
Make sure the animation clip itself is not set to loop
Thank you so much
I thought i was getting crazy
like this? if so how do i get it in the space because this is a prefab
perhaps chat gpt could help
Scene references can be set by a scene object instantiating the prefab.
spawnedMiddle.Logic = ...```
ok nothing really makes sense il just watch a few more tutorials and come back
hello I have the hp bar fixed but I want it to display the currenthp with the maxhp with a text component how to do it
plenty of tutorials around for that
Have whatever object holds those values set the text property of a text component to those values
public void SetData(Pokemon pokemon)
{
if (pokemon == null || nameText == null || levelText == null || hpBar == null || hpText == null)
{
Debug.LogError("One or more components are null!");
return;
}
nameText.text = pokemon.Base.Name;
levelText.text = ":L " + pokemon.Level;
int currentHP = pokemon.CurrentHP;
int maxHP = pokemon.MaxHP;
hpText.text = currentHP + " / " + maxHP;
hpBar.SetHP((float)currentHP / maxHP);
}
I have this code so far
public int MaxHp {
get { return Mathf.FloorToInt((Base.MaxHp * Level) / 100f) + 10; }
}
and have this for calculation of hp stats but it shows a higher value than what I intend on is the formula wrong?
Check the formula by doing the math yourself. See if the value you get matches the value you expect
I got the formula from official website
And also how to make it reduce the text when the filled healthbar is reduced that we did yesterday
Why isn't my code working to set the position? The red cube is the transformPoint that it's meant to be following.
void Update()
{
Vector3 screenPoint = cam.WorldToScreenPoint(transformPoint.position + offset);
rectTransform.anchoredPosition = screenPoint;
}
when i look at the position of the texts, they are way off.
Are you sure you actually want that? After about halfway there won't be room for any text.
No like the text is beneath the health bar
First off as a sanity check - remove offset from the calculation. Does it go where you expect then?
So, position the text below the healthbar when you make it and then don't move it
nope
Does this https://docs.unity3d.com/ScriptReference/RectTransformUtility.WorldToScreenPoint.html work any better?
NVM I just checked the source code and it just calls camera.WorldToScreenPoint 😐
It is but I am saying of adjusting the int value accordingly
yeah lol, exact same outcome. what is the point of the difference then 😭
I have done that but when my HP is reduced the int value doesn't get updated
@stuck palm IIRC anchored position is like local position, maybe the UI object's parent is in the wrong place?
its just at 0,0
Actually you should try this
https://docs.unity3d.com/ScriptReference/RectTransformUtility.ScreenPointToLocalPointInRectangle.html
With the parent transform as the rect
Did you change the text after the hp changed?
okay one sec
So first WorldToScreenPoint, then that
I wrote the script I attached it
That didn't answer my question
This one
The text should change the current value as I have assigned it
So, it sets the text when SetData is called. Is SetData called when the values change
Yes exactly
Log the values of current HP and max HP after you set the text.
If you get the logs and they don't match the text element, either you're changing the wrong text element or something else is changing them back afterwards
Ok thanks for the help will update you
void Update()
{
Vector3 screenPoint = RectTransformUtility.WorldToScreenPoint(cam, transformPoint.position); // + offset;
RectTransformUtility.ScreenPointToLocalPointInRectangle(parent, screenPoint, cam, out Vector2 localPoint);
rectTransform.anchoredPosition = localPoint;
}
just completely off the map now
why not just use world text
i might just do that honestly
how can i make it like
a billboard?
so it constantly looks at the camera
i mean look at sounds easier
i'll just make world canvases and stuff
thanks! didn't even think of world text lmao
Idk why unity makes this so hard
I barely use Unity UI so I don't really remember what's the right way to do it
me neither, but it's probably something to do with my weird parenting mess. everything is positioned at 0,0 so it shouldnt be a problem though
yeahhhh just too much work
All I can think of is pivot on the UI text isn't representing it correctly
or margins on the text
can you not assign scriptable objects at runtime? ive got a script that holds a list of scriptable objects, and i try to grab the reference to a specific index at runtime and it just refuses
provide more information about what is actually happening, including relevant code
i might have noticed the cause, ill come back if it isnt it
my character is 32x64 and these tiles are 32x32 but the tiles appear twice as large as they should (using a tileset/grid). cant figure out why. the scale of each is set to 1. i double checked that the tiles actually are 32x32
this is a code channel. and you likely need to adjust the pixels per unit setting on the import setting for the texture
how do I cast a SphereCast where I want to ignore triggers but detect all Layers?
pass QueryTriggerInteraction.Ignore to the queryTriggerInteraction parameter
why dose it think that its a int?
Physics.SphereCast(jumpSpherecast.origin,0.5f,jumpSpherecast.direction,out RaycastHit hit,0.755f,QueryTriggerInteraction.Ignore)
(jumpSpherecast is a Ray)
error says: cannot convert from 'UnityEngine.QueryTriggerInteraction' to 'int'
(the error is for QueryTriggerInteraction.Ignore)
pay attention to the parameters required
https://docs.unity3d.com/ScriptReference/Physics.SphereCast.html
and maybe give this a read too https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/named-and-optional-arguments
I know but I want to dettect all Layers
Is LayerMask required to be declared to declare QueryTriggerInteraction?
public QueryTriggerInteraction triggerInteraction = QueryTriggerInteraction.Ignore;
void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
{
if (Physics.SphereCast(transform.position, radius, direction, out RaycastHit hit, distance, ~0, triggerInteraction))
{
Debug.Log("Hit: " + hit.collider.name);
}
}
}```
you could use `~0` in place of the layermask
that'd be ur Default layers (all layers but the Ignore Raycast layer) iirc
That will include all layers. If you want the actual default, use Physics.DefaultRaycastLayers
aye 
i was thinking you didn't need a layermask at all.. but im guessing you do to get to the seventh parameter
correct, I had to test for myself..
ive seen ppl say ~0 is the same as DefaultRaycastLayers and some say its different..
Read the information in both links I sent
~0 is all layers, including ignoreRaycast
cool that it includes all the layers, even the unused ones..
yup, jotted it down for future reference.. its one of those things that i keep forgetting about
always having to go and double-check lol
public void PickUpBox(InputAction.CallbackContext context) {
if (context.performed) {
if (Physics2D.OverlapCircle(directionPoint.position,0.2f, boxLayer)) {
//get gameobject
}
}
}
What i want to do is, get the Gameobject that is at the directionPoint. This there a way to get this just via script of do i have to use a triggerCollider ?
thx guys
can you check the Y coordinate and compare it? if its less than its beneath?
or is that not accurate enough?
sorry maybe it was unclear, i want to access the gameobject, that is on the dectionpoint, to do thing with it.
and store this GameObject aka the Box in a varible
OverlapCircle returns a Collider2D array (I believe) so you could probably grab the object(s) from that
I'm trying to create some sort of a simple plane flight demo.
As you may know, the force of lift is dependent on velocity ^ 2.
I use Rigidbody.velocity.magnitude to get this velocity, and use the standard formula for lift.
My trouble is, when the velocity exceeds a certain point, my simulation goes into a self-sustaining infinite loop in which the velocity and force of lift go into infinity.
Any idea how to prevent it?
cap it
is ur lift creating forward momentum as well?
if (Physics2D.OverlapCircle(directionPoint.position,0.2f, boxLayer,results) {
resultes[0].aktivedMyFunction
Won't work right? if i get the collider2d, how to get form the Collider to the entire GameObject
It should not, the lift vector is perpendicular to the plane's y-axis (btw it's a 2D game)
you can get .gameObject from collider
okay thx, i will try this
the easy answer has already been presented.. "cap it"
otherwise add dynamic drag
unsure why u have infinite loop tho.. if the lift is only perpendicular to the plane
well if you want the collider of multiple objects you would loop through the colliders and grab them and use them, if you only want the first one you need to do
Collider2D[] stuff = Physics2D.OverlapCircle(Center, Radius, Layermask);
Stuff[0].transform.gameObject;
liftForce = 0.5f * liftCoeffient * 1.225f * Mathf.Pow(rb.velocity.magnitude, 2f) * wingArea;
Vector2 liftVector =Vector2.Perpendicular(transform.right) * liftForce;
Maybe I did something really weird here?
But yes I'll cap it
In practice only forward velocity generates lift. So using magnitude isn't correct. It should be rb.velocity.x
Oh that might be it
And what keeps lift from increasing to infinity in real life is drag, so you might want to model that in too
You have two things that can be null there
lol i just realised
i didnt attach the actual SoundReceiver script
i know i shouldnt be using gameobject.find but i just wanna know why is this not finding the gameobject
i used this same script with the same setup of objects on a different scene and it worked, but its not working once i bring the prefab into a different scene
it finds the gameobjects on start
Are you spawning the player at runtime?
no its just in the scene
im pretty sure everything is the exact same as in the test scene but its not finding anything (im using multiple gameobject.finds)
Is the script doing the searching in the same scene as the player?
I assume you don't have any sort of multi scene setup going
i think it is
the script is attatched to an enemy that when it spawns just searches for stuff it needs to work
I assume that line is currently throwing a null ref exception?
yeah every time it spawns
it says } is expected but i already typed it
still need one to close the class
add another one at line 58
A lot to guess. Posting the full hierarchy in edit mode, in play mode and the full script used to search could help
thanks i must have deleted it by accident
You could use GameObject[] rootObjects = gameObject.scene.GetRootGameObjects(); to get all root objects just before the search and log through them all in a loop to see every root object at that time.
Is the player object or CamContainer disabled when that search happens?
https://hastebin.com/share/sadoxehazu.csharp
the selected object on the second screenshot is whats searching
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
You sure you don't deactivate the objects you are searching? GameObject.Find does not find disabled objects.
is "Player/CamContainer" correct?
this is rly weird bc its finding the objects but it just isnt assigning them also theyre not disabled
i didnt even know thats how that works
im gonna guess that it indeed is finding things.. but ur getcomponents are failing.. (maybe b/c they dont have the components)
ran the same code, from a prefab in Start() using same heirachy and strings.. and it worked fine
It wouldn't throw on that line if something was found
all the objects have the components tho so idk whats wrong with it
maybe its a bug on my unity version idk
even w/ the .GetComponent<>?
sorry i didn't catch the line-number of the error
Only if nothing was found
it would only throw if GameObject.Find failed to find anything, GetComponent would just return null if Find was successful but that component wasn't attached