#💻┃code-beginner
1 messages · Page 13 of 1
for context:
red = array, green = list
actually after taking a step back I will probably have to refactor a decent bit of what I've started just to make integration with the ui a bit simpler, oh well time to sleep
looking good
If the slots are named you should use a struct
To be honest even for the unnamed one you probably should
Actually, to be honest, if you have nullable fields (e.g. they can be empty) a dictionary indexed by an enum might be more appropriate
helo everyone i am stuck at some point whene i want to add more prefabs in the script of manomotion sdk and then i want them to change/spwan/loop these prefabs on ui button click.... but i donno how to achieve this!!! here is the script and the sdk is used giving by manomotion sdk for ring try-on example
https://paste.ofcode.org/RwAgCJkk8NkrvAPjrGc2JL
can anyone help em out in this?
Please use a !code paste site, people cant read this code on a phone.
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
here it is ... and i am sorry i didn't know about that..
No problem, now you do 
ys
so is ther any solution regarding it ?
when smelting finishes i get an error on line 123
it removes the item from the cell and etc, it just doesnt spawn a new item
the outcome
wait it does spawn it
but i get an error
Can you click the error and show the stacktrace? I think the problem lies inside the GetProcess function
i just left for college
i can when i get home
idk if your still gonna be willing to hell
but thats all i got for now
its not the GetProcess because before it worked when i didnt have multiple input cells
Should post it in the forums if you need archiving. People will not check old messages on Discord.
it worked when i didnt have the foreach inside the foreach
Or maybe a thread with "I'll be back later. No extra details are available."
Don't know, but I think the full stack trace would be useful. It might also be that you are foreaching over a list with null values in them. Anyhow, good luck.
I think it's due to iterating a sub collection/array but modifying the path (item). Who knows though 🤷♂️
inputCell.cell.Remove();
Destroy(inputCell.cell.item.gameObject);``````cs
inputCell.cell.item.GetProcess(ProcessTypes.ProcessType.Smelt).processOutcomes```
I'm making a game where you need to catch falling coins, your score goes up with each coin you catch. Is there a way to make it so the score only increases when the coin lands in the catcher? (at the moment if the coin touches the catcher at all the score goes up, even if you didn't properly catch it)
Also possible, just a bit dumb that he throws a question out and then can't provide answers for hours...
Define catch.
It lands in the chest (the catcher)
So maybe make the trigger event smaller? (had to be fully caught)
I'm unaware of your setup.
When would it not land in the catcher but still be counted. You'll need to define/understand the edge cases.
At the moment I'm using the mesh collider to register the collision
Example: It's considered caught when the velocity of a coin is minimized below a certain threshold but within proximity or making contact with a bucket etc.
At the moment the score increases if it makes any contact with the chest. I'm trying to make it so if the coin hits the sides nothing happens but if it lands inside the chest the score goes up
So score goes up if the coin goes in the green but just bounces off if it hits the red
Seems like you just need a smaller trigger area which is inside the box then, that trigger area being what really increments the score
As suggested above
I'm very dumb, how do I make a trigger area in the chest?
As I said I'm just using a mesh collider rn
What do I script to make it differentiate between the two different colliders?
You can just use a box collider for the inside area, then checkmark the trigger option.
To differentiate between the 2, drag the correct reference in from inspector for what you want and use [SerializeField]
From the inspector to where?
This would be entirely within the inspector, where you would drag the box collider into the appropriate field
If you opt to use another object such as a box (child), you can make it invisible by disabling the renderer and set IsTrigger to prohibit collision etc.
does anyone can help me out please!!
Using a box as a child and having the script on there instead of the chest works, thank you
Thank you to you as well
So you want some prefabs to spawn when you click a UI button?
yes
Use inatantiate to spawn them and use the TMP buttons which make it really easy to connect functions to button clicks
umm where should i modify my script that is already attached to it
Don't really know, but you made the code (i hope) so just make a button and a function inside the script which spawns the prefabs and connect the button click to the function in the editor under the "onClick" section of the button
i didn't made the code it was inbuilt in it with sdk sample.... ok i'll if i could see anything to modify it
Need a simple way to create a slide physics with a way to control it without using Spline.
https://www.youtube.com/watch?v=m6DgiSGeHD0
This type of sliding + "path" along which you can slide.
In that case I doubt you have anything to change other than just adding a function yourself which instantiates the prefabs
umm ok i'll try something with this
//Camera
transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivity, 0);
cam.Rotate(-Input.GetAxis("Mouse Y") * sensitivity, 0, 0);
//Movement
rbLateralVelocity = new Vector3(rb.velocity.x, 0, rb.velocity.z);
Vector3 tgtMoveDir = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")).normalized;
if (tgtMoveDir == Vector3.zero) rb.AddForce(-rbLateralVelocity * removeSpeed, ForceMode.Force);
else if (rbLateralVelocity.magnitude < tgtSpeed) rb.AddRelativeForce(tgtMoveDir * addSpeed, ForceMode.Force);
//Jumping
Vector3 v3 = new(transform.position.x, transform.position.y + 1, transform.position.z);
if (Physics.Raycast(v3, Vector3.down, out RaycastHit hit, 1.1f))
{
isGrounded = true;
}
else
{
isGrounded = false;
}
if (Input.GetKeyDown(KeyCode.Space) && isGrounded) rb.AddRelativeForce(Vector3.up * jumpHeight, ForceMode.Impulse);
}```
currently having a weird issue where every time i land from a jump, my lateral velocity is reset to 0
Code seems fine, is this in FixedUpdate?
Also, can you add the debug.logs again like last time? Knowing what kind of AddForces you do is important.
well, i just tried moving the AddForce lines to FixedUpdate() and now i cant move at all 
Well using AddForces in Update causes wonky stuff to happen.
Physics functions need to be in FixedUpdate, read the docs about it. Anyhow, good luck.
aaand also running into the issue where if i walk into an obstacle it starts rotating me
ive figured out the jump thing, it feels a lot better if i just make the jump smaller
Physics forces can be done in Update if they're instantaneous (impulse etc)
how can i make it so the notebook updated text only happens once?
add a counter or a bool that changes when this happens, if the counter or bool already is changed then dont do the "Notebook updated" text
Please properly configure your !ide before requesting help regarding your code in this server.
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
ive tried so many times. jetbrains isnt workingas it should and the VS plugin has made my editor worse than before. somethings gone wrong
Visual Studio has a single workload you need to download. Then it's just a matter of specifying the editor to use in your Unity Editor. Perhaps try that.
I don't know about Jetbrains, but I do know you should definitely not use Visual Studio Code for Unity since the support is very bad (I guess that's what you mean with plugin?)
I'll uninstall everything and start from scratch with setting it up
Feel free to message me if you get stuck. I do have a long ass meeting in 40 minutes but I'll try to answer.
I appreciate that. I'll get on it now
is it possible to make an inspector property that holds 2(or more) floats(from 0-1) in a single slider?
via custom editor
i did think that. Thank you.
hello, i did player controller and its ok for me, but it have an problem, when i colide with any object it stop moving, but if i dont press horizontal buttons it falling down, is there any tutorial on youtube how to fix it or can you help me?
Depends if you're using rigid body or character controller.
rigidbody2D
It seems like you are simply checking if the player collider touches something in order to consider yourself touching the ground
But I am just making assumptions since you haven't actually shared your !code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Yes so notice how the check for grounded checks for a collission with something that has the Ground tag. This is the platform you hit, and this causes the velocity to reset.
It is not a good idea to have such a simplistic system for this. Instead you want to make a second collider just below the player, which will check if it collides with anything at all. The player collider is then just a simple collider
... its a wall... but, it colides ground too
If you want to improve it even more, you add a seperate collider on all sides, and you can then determine if you get hit on any side. For example, if you run right and the right collider has a collission, you can reset the velocity
I don't know, but your current system is very flawed since it has no proper knowledge on where you are actually hitting the ground on.
So as I said, you should probably make multiple colliders for each side, or you need to somehow determine on what side the collission is coming from
I personally make multiple colliders since it is simpler, and then I maintain a context of what sides are being hit at that point.
i fixed it with this:
if (walled == false)
{
rb.velocity = new Vector2(move * speed, rb.velocity.y);
}
private void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.CompareTag("Ground"))
{
grounded = true;
speed = setSpeed;
walled = false;
}
if (other.gameObject.CompareTag("Wall"))
{
walled = true;
}
}
so, when it colides only with wall it wont be able to move, but if it colides with ground too it will be able to move
cuz im new to code and i dont know anything better than this
greate.. i dub... i got another proble ny doing this...
i hate to learn ore about how to code..
A quick question, I have a grid menu for mission select that currently uses mouse input and I would like to add controller and keyboard support on top of that. What do you suggest?
public AnimatorController graphicsShowcaseAnimatorController;
public AnimatorStateMachine animatorStateMachine;
public AnimatorState animatorState;
these variable types are using UnityEditor.Animations namespace. If i understand correctly, I cannot use them in build, just in the editor?
how can i use these variables in the build? I kinda need them
You can't. Store the data in some other way/ custom class/struct.
How to let AGameObject position move to BGameObject position
gameobject.transform.position
I want AGameObject like Animation move to BGameObject just like gun shooting
transform.position
Over time
For example you could lerp between origin position and the target position.
I would use https://docs.unity3d.com/ScriptReference/Vector3.MoveTowards.html
Super simple and straight forward to implement.
Thanks you
My intellisense isn't working like it should (or at least how I'm used to it working) and visual studio isn't showing me errors. I have to save the script and go back to unity to see errors in the console. Is there something I need to enable/install or is it just messed up for whatever reason?
Can you show a screenshot of your whole VS?
It isn't configured, read the !vs guide on how to configure it for Visual Studio
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
Just didn't want to work the first time it seems haha
A restart is required yeah

!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
How to solve it
Read the actual error, it tells you on which line the problem lies.
it say Enemy line 37 is problem line but I don’t have a idea to fix it
Did you go through the doc, and understand what the cause is, and also get to the part where it talks about resolutions for the type of object you're dealing with?
Hello Random.Range in the unity docs say its both minInclusive and maxInclusive but in Visual Studio it says its minInclusive maxExclusive I am like 90% sure that the docs are correct but someone is telling me theyre not can someone smart clarify which one is correct for me?
you might be looking at the float vs int overloads for it @edgy prism
https://docs.unity3d.com/ScriptReference/Random.Range.html
notice in the docs there are 2 versions
Ohhhh ok I am
float is both min and max inclusive
int is min inclusive and max exclusive, its done this way so the random range on ints would be valid indexs
for example
var id = ids[Random.Range(0, ids.Count)]; would be valid code since ints are max exclusive
Thankyou for clarifying
Hello, friend! When in your code arising errors like this one, then you have to think that you forgot either something in your inspector of an object for example a value that you didn't save or there is a null reference and you don't initialise the field/variable of the object that's the most common errors but still sometimes they can be complicated XD
Well, he's trying to use GetComponent<Bullet>() on the GameObject with the Enemy script
He most likely wanted to do it on the newly Instantiated Bullet
Leaving aside the part where he could just reference the Bullet script instead of the GameObject and instantiate that
I barely see what the code says why he didn't take a screenshot from his pc and take a photo from his phone
Maybe he doesn't have discord on his PC because he doesn't want his mom to see his discord dms
Either way, it's readable enough
Sign in to the discord web application
If you have a magnifying glass at hand
Posting photos of your screen is awful
My mouse position aint being updated. It somehow has the position of the first block in spotList https://gdl.space/pebetoqedo.cs
is this a 3d game?
If it's a perspective camera, cam.ScreenToWorldPoint is only going to return the camera's position the way you're using it
yeah ScreenToWorldPoint is the wrong approach here
Use Plane.Raycast
(or just use ScreenPointToRay plus a raycast)
ah yeah, that's the second option on that page
Everyone gets tricked by that perspective camera behavior at least once
Hello. I want to disable collision between player and dead enemy bodies, so I've created this function
public void DisableCollisionsWithPlayer()
{
foreach (RagdollComponent[] ragdollComponents in ragdollComponents.Values)
{
foreach (RagdollComponent ragdollComponent in ragdollComponents)
{
ragdollComponent.collider.gameObject.layer = deadEnemyLayer;
}
}
}
that sets collider object's layer to deadEnemyLayer set through inspector, and I've disabled collision between player and deadEnemylayer layers, yet my player still collides with the enemy dead body. Any ideas why?
Perhaps there are other colliders on the enemy.
Log the exact collider your'e hitting
Okay i figured it out, the layer is not changing
its still on Enemy layer
did i change the layers wrong in code?
can you show how you declared deadEnemyLayer?
it is supposed to be on DeadEnemy layer
does it happen to be a LayerMask
public LayerMask deadEnemyLayer;
yeah, that won't work
ow
a LayerMask is a combination of layers
basically, 32 layers get packed into a 32-bit integer
oh yea true
each bit is a 1 or a 0 for yes or no
You want to use LayerMask.NameToLayer to convert a name to a layer ID
I don't know if there's a way to just pick a single layer ID in the inspector
ragdollComponent.collider.gameObject.layer = LayerMask.NameToLayer("DeadEnemy");
you probably can..
But yeah, that'll work just fine
You were probably setting the layer to a really big number
I dunno what the exact behavior is. It might give you an error.
Afaik you have to make/find a property drawer
No idea why there's no property attribute for it
I got this code from brackey's, movement script for single player
and tried to change it for multiplayer
but I can't seem to look to the left or right
Remove the * Time.deltaTime; btw. It's a known bug in that tutorial
you'd have to share your code and other setup for the attempt
Do you get any errors
I'm not getting any errors
and it seems that the camera wants to go to the left and right but gets stopped
sounds like a bug in your code
e.g. you're setting the rotation to the mouse input instead of adding the mouse input to the rotation
it shakes shortly when I try going left or right
but without seeing the code, can't say for sure. Just guessing
What is Player set to
Code looks fine. The problem will either be due to how you set things up in the scene or some other script.
or perhaps from the networking aspect
This is the player prefab
for example, does the client have permissions to actually rotate this object
Didn't change anything saying that it shouldn't so I don't know why it would :x
Leak Detected : Persistent allocates 75 individual allocations.
What does this mean? How do I fix it?
Is that MouseLook script rotating itself? You should have a separate object doing left/right than the one doing up/down
Are you using the job system?
Yes
Player should be a different object, like in the tutorial
yeah that mouse look script is expected to be on a child object of the Player object
the way you have it, it's going to reset the rotation constantly
with transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
see how you're setting y rotation to 0?
It's intended to be:
Player
Camera (with that script, pointing at Player for the Player reference)```
that's how that tutorial is structured
I am using the job system, I got some text from the console
indeed that was the problem, put the script on the player camera
and then put the player gameobject inside the script
and that fixed it
thanks @toxic geode @wintry quarry @polar acorn @north kiln
I have a problem... Im programming with unity for 2 days now and i dont understand this whole collider thing its just weird if im too fast im glitching under the map if im normal and i collide with something all controlls are screwed up, here: In the second phase after i collided with the cubes im only pressing S and its making a curve why is that?
Without showing us how your objects are set up (what components they have, how they are configured) and also without seeing code, we can't really help
how do i send code?
the answe to your question is: because your code and scene are set up in a way that causes that.
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private float dirX = 0;
private float dirZ = 0;
private float speed = 5;
void Start()
{
}
// Update is called once per frame
void Update()
{
dirX = Input.GetAxisRaw("Horizontal");
dirZ = Input.GetAxisRaw("Vertical");
transform.Translate(new Vector3(dirX, 0, dirZ)* Time.deltaTime * speed);
}
}
you're moving via transform.Translate. That explains all the physics glitchiness
ah i should do it via velocity right?
Via a Rigidbody or CharacterController
what is better?
hm ok i will google the difference but thank you
Both of them are designed to do certain things easily, but at the expense of other things becoming harder. It depends on what kind of movement you want
the easier one
Both of them are designed to do certain things easily, but at the expense of other things becoming harder. It depends on what kind of movement you want
you have been presented with an apple and an orange and you said "Give me the easier one"
A CharacterController is designed to move in a way that respects colliders. It can never be affected by physics forces.
A non-kinematic Rigidbody is affected by physics. It will feel gravity (by default) and be shoved around by other physical objects
If your character's movement involves lots of physical interactions (e.g. getting launched by a flying platform or bouncing off of walls), then a Rigidbody is a good choice
If you want strict control over movement, then a CharacterController makes more sense.
hm ok i tried it with a rigidbody but now i get: Screen position out of view frustum (screen pos 768.000000, 760.000000) (Camera rect 0 0 1467 762)
UnityEngine.SendMouseEvents:DoSendMouseEvents (int)
couldnt find something on the internet the posts to this error are even older than me xD
I tried to delete the auto created Camera and manually created one but it didnt work
Did you try changing the view frustrum?
You're trying to get a screen point that isn't inside the screen
camera script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Camerascript : MonoBehaviour
{
[SerializeField] Transform player;
void Start()
{
transform.eulerAngles = new Vector3(50, 0, 0);
}
// Update is called once per frame
void Update()
{
transform.position = new Vector3(player.position.x, player.position.y + 12, player.position.z - 10);
}
}
ah i solved it nvm
No but there's an And and a not that you can both use
so many bugs with this movement thing, when i go against a wall while falling down i stop falling and if i go up a ramp i jump when i stop
How are you moving? Rigidbody, but with addforce, velocity, or MovePosition? I assume velocity?
And sorry, missed your question earlier. A frustrum is just the capped pyramid shape (is it called truncated pyramid?) that represents what the camera can see.
velocity
So, a pitfall of that, is that if you are setting the velocity by making a vector from horizontal movement, and use a 0 in the y position, you are telling it to have 0 velocity in the y direction. Thus, you hover and won't react properly to gravity
Ah, ok, that is the right way to do it
that if i implement jump later that it doesnt get overwritten by it
Maybe something to do with your ground check then? Is it a raycast or overlap?
Ok hmmm. I'd need to see code to comment further then.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private Rigidbody rb;
private float dirX = 0;
private float dirZ = 0;
private float speed = 8;
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
dirX = Input.GetAxisRaw("Horizontal");
dirZ = Input.GetAxisRaw("Vertical");
rb.velocity = new Vector3(dirX * speed, rb.velocity.y, dirZ * speed) ;
}
}
problem:
(i dont have a jump button or anything)
Ok, so the issue might be that when you go up a slope, it gives you a bit of y velocity. Then you keep setting it to that given y velocity for a little bit after you stop. You probably need a ground check to tell when you're on a slope and set it to a negative y velocity until on flat ground.
The falling thing may be a friction issue? Does it happen if you don't fall AGAINST the wall, but fall from midair?
but then i cant jump on the slope right?
If you jump, don't set the velocity to a negative
It's gonna get complex haha
but why is that complex xD i just want to make something simple
if you roll something up a ramp, it will gain upwards momentum
Character controllers/physics are not simple. That's a misconception
to make something that seems simple to a user is often quite complex behind the scenes
yeah but i see all those yters that say "yeah im going to do a simple prototype" then the cut 10min after and have a simple movement script camera script and a pathfinding thing that tries to attack the player
doesnt sound complex thing
Youtubers lie
but i just want to do a "simple prototype" xD
Also pathfinding isn't a character controller
Then just do a character controller. It will be less boilerplate
It will introduce others haha
But it miiight be more conceptually easy? I dunno
I use velocity and addforce
man roblox programming was simpler... xD
Roblox holds your hand
Well yeah, it is also way less versatile
Unity is a real game engine
with unlimited possibilities
with those unlimited possibilities comes complexity and having to deal with the ugly intricacies of things
but where do i start?
You can find assets on the store if you want (including free ones).
A popular one is the kinematic character controller
If you want, there are plenty of off-the-shelf character controllers with lots of things handled already
Yes KCC for example^
no i dont want to copy paste things i want to do it myself and learn it
do tutorials then
but realize that straying off the specific thing the tutorial is doing is going to often be difficult
the ability to actually do things on your own comes from lots of experience
you need to do the stupid simple things first so that the way the engine works starts to click in your brain, then you can start innovating on your own
Then you do it again, and that time you'll remember it for two hours
Then again and you keep it for four
and so on until you don't forget it
from where should i get the motivation to do this?
is it easier to start with 2d or is 2d and 3d completly different and 2d knowledge will give me no advantage in 3d?
that's your issue ¯_(ツ)_/¯
2d is 3d in unity to some extents. A lot is transferable
How badly do you want to learn Unity?
If it's not that badly, then maybe pick another hobby.
i dont think that you guys all had unlimited motivation
did you start with 2d or 3d?
@wintry quarry
what do you suggest me
2.5d
4d
is it better to do 2.5d in 3d or in 2d?
Ultimately that is just a distinction of camera angles and renderer types
the rest of Unity is still Unity
you will learn Unity either way
there's no difference betwen 2d and 3d in unity
just a camera angle
what would you do
wdym
would you do such a project with 2d or 3d
there is no difference
what would you click in the menu
you're talking about project templates
all those do is give you a set of starting packages and camera settings in the scene
If you want 2.5d that's basically just a 3d game
where the character can only move on one plane
Either template can get you there
Someone help me with this
Wdym sect?
a religious group xD idk
Ohhh praetor? That is actually a government official haha. But it's just a name, I assume. Unless they are from ancient rome? Who knows
what are you talking about haha
What are you talking about?
lets just forget what happened
I don't understand how it wasn't clear. The word praetor is an elected official. It is still used but the first definition is:
"An annually elected magistrate of the ancient Roman Republic, ranking below but having approximately the same functions as a consul"
So I made a joke lol
...?
im german i cant understand english jokes
Whose name is only a letter?
bro gotta take a nap
all of you
My name is "Aethenosity" in here
No one's names are only a letter
wait what
That is... multiple letters
Are you in streamer mode in discord
Ah, so my joke was even more confusing. The guy you were talking to is named PraetorBlue lmfao
Next time you see something weird in the discord, probably keep it to yourself
i think i should do haha
"There's a man on the wing of this plane! You gotta believe me!"
unless you're watching Death Note
Please stop 
Yeah we're off topic
Apologies. Will do. Should have known better haha
back to the topic of helping me 🙂 with what do i have to replace the 0 in the move y direction when im using character controller
because right now the gravity isnt working
For a Character Controller you need to handle gravity yourself
A negative value when appropriate
SimpleMove automatically handles gravity for you, which is an option.
It takes a velocity, not a distance
it just adds to your old Y velocity and includes that in the move
Otherwise, you'll want to take your old Y velocity, add Time.deltaTime times the gravity strength, and then include that in the move vector
best way to add 2 weapon stats variables together, floats get added, booleans turn into the one that is being added and rest stays the same
write a function that does it
perhaps even think about overloading the + operator
what do you mean overloading
this is how Unity makes it so you can do cs Vector3 a = Vector3.one; Vector3 b = Vector3.one; Vector3 c = a + b;
they overloaded the + operator
you can do the same thing for your own custom classes
the example is hell to read
it's like 6 examples in one
Each one of them is one simple exmaple:
public static Fraction operator -(Fraction a, Fraction b)
=> a + (-b);```
this is a complete example
This is also a complete example:
public static Fraction operator /(Fraction a, Fraction b)
{
if (b.num == 0)
{
throw new DivideByZeroException();
}
return new Fraction(a.num * b.den, a.den * b.num);
}```
well now thats what Im talking about
so in my case
what does it even mean to overload an operator?
does it mean it can now work in different use cases?
It means you change what C# thinks that operator means for this object
Like, instead of "addition", you can make + mean "Run this function"
It lets you use the operator with your custom types
normally if you did cs public class Example {}
You can't just write:
Example a = new();
Example b = new();
var result = a + b;```
That will be a compile error because it has no idea what Example + Example even means
by overriding the operator you are telling it how to do Example + Example
so it will let you write that code
also can I run thru all class varibles
like a foreach does to a list
no
if you want to do that you could/should put these stats into a collection of some kind
For reasons like that, I often find that a better structure than:
class Stats {
int hp;
int armor;
}```
Is something like:
```cs
enum StatType {
HP,
Armor
}
class Stat {
StatType type;
int value;
}
class Stats {
Dictionary<StatType, Stat> stats;
}```
Then you can do something like:
Stats AddStats(Stats a, Stats b) {
DIctionary<StatTye, Stat> result = new();
foreach (StatType st in allStatTypes) {
result[st] = new Stat() { type = st, value = a.stats[st] + b.stats[st] };
}
return new Stats() { stats = result; };
}```
just as a quick dirty, non compiling example
otherwise - you're stuck manually adding everything
which is really not the worst thing in the world
you only need to write it once
and then just update it whenever stats fields change
thats true
maybe I'll go with that since its the simplest and less complicated way
also it is way more optimized
So the function GetDownloadHandlerAsync does yield return on the first Function provided. I'm getting errors saying I cannot call yield in these functions, would calling return in an IEnumerator function being ran as a coroutine give the same result as calling yield return or do I need to change my approach?
I'm getting errors saying I cannot call yield in these functions
Sorry what is the exact error mesage you're getting here? I don't see any errors in your screenshot.
In general you cannot mix yield return with regular return statements in the same method if that's what you're asking?
ah alright, that is what I was asking thanks
if you have an IEnumerator that you want to basically return instead of yield returning all your own things inside a coroutine, you'd basically have to do this:
foreach (var thing in theEnumerator) {
yield return thing;
}```
Another option in this context if it's a coroutine is to just yield return theOtherCoroutine;
which is what you're doing now but you said you're getting some kind of error?
It was an error telling me I can't put yield in an anonymous/lambda method
on which line exactly>?
You'd have to show the exact code and the exact error
nvm, just found an alternative way of doing it
but I can try and replicate the error again one sec
NullReferenceException: Object reference not set to an instance of an object
Furnace.HandleAssembly () (at Assets/Player/Interaction/Furnace.cs:123)
Furnace.Update () (at Assets/Player/Interaction/Furnace.cs:37)```
if anyone can help me with this
Hello I have this small code the goal of it is just to add x rectangle gameobject to a list of rectangle when I print the len of the list it show me the right result but when I print the content of it it seems to have "null" value I don't know why (I have the rest of the code but it's not usefull for that problem)```csharp
using System.Collections.Generic;
using UnityEngine;
public class EntitySpawner : MonoBehaviour
{
private GameObject spawnedEntity;
private GameObject spawnedEntity2;
private List<GameObject> weaponsListDown = new List<GameObject>(); // Liste pour stocker les armes des anciens ennemies
private List<GameObject> weaponsList = new List<GameObject>(); // Liste pour stocker les armes
private List<int> weaponstypeList = new List<int>(); // Liste pour stocker les armes
private float spawnRange = 5.0f;
private bool entitySpawned = false;
private int life = 100;
float WeaponType = 2;
private void Awake()
{
for (int i = 0; i < 3; i++)
{
WeaponType = UnityEngine.Random.Range(1, 3);
if (WeaponType == 1)
{
weaponsList.Add(spawnedEntity2);
weaponstypeList.Add(1);
}
else
{
weaponsList.Add(spawnedEntity2);
weaponstypeList.Add(2);
}
}
UnityEngine.Debug.Log($"w {string.Join(", ", weaponsList)} {weaponsList.Count}");
}
}
Reading stack traces, something is null on the mentioned line but you're trying to do something with it anyway!
Furnace.HandleAssembly () (at Assets/Player/Interaction/Furnace.cs:123)
^~~~~~~ ^~~~~~~~~~~~~~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ^~~
CLASS METHOD PATH LINE NUMBER
Either inputCell or cell or item is null. Basically everything on the targeted line that appears before a . could be null, find out what it is
You circled two lines and didn't include line numbers in that screenshot, so I'm taking the broader cases
i just tested it, when i have more than 1 item in the inputCell
it works
because you arent destroying it
but if its one item in the input cell
i get the error
So it's on line 123 as the stack trace mentioned (did you read my message about how to read a stack trace???), not where you circled the code
Anything that is followed by a dot . on that line could be null, you need to do some debugging
private void HandleAssembly()
{
foreach(FurnaceCells inputCell in inputCells)
{
if(inputCell.processTime == 0 && inputCell.isProcessing)
{
inputCell.isProcessing = false;
inputCell.processTime = 0;
//inputBar.fillAmount = 0;
foreach(ProcessOutcomes outcome in inputCell.cell.item.GetProcess(ProcessTypes.ProcessType.Smelt).processOutcomes)
{
Item newItem = InventoryManager.Instance.Spawn(outcome.item, outcome.amount);
Add(newItem, newItem.amount);
}
if(inputCell.cell.item.amount > 1)
{
inputCell.cell.item.amount -= 1;
inputCell.cell.Refresh();
}
else
{
Destroy(inputCell.cell.item.gameObject);
inputCell.cell.Remove();
}
}
}
}
this works
but i dont know why
You're not going to solve all future issues by moving code around randomly until it works
Learn how to debug things
There are guides pinned to this channel
now its checking every inputCell there is, and if the input cell finished processing, then straight away set the isProcessing and processTime to false and 0, which will unable the rest of the code to run again
before since the isProcessing was being set to false at the bottom, the foreach was running a lot more times than it should
Okay seems like you're not reading what I'm saying nor taking advice, I'm out, good luck with your issue
inputCell.cell.item
hey everyone I'm new to Unity and was working on a flappy bird type game using the Game Maker's Toolkit Unity tutorial and ran into this error, however I cannot find any problem with this code
What is the error
You are trying to get a component from an array of objects with that tag. Arrays don't have GetComponent, you'd need to tell it which one you want the component from
GameObject[] means "An array of GameObject"
you can drink a can of soda, but you can't drink a 12-pack of soda
you can't drink the box
that would hurt
Try me
slurp
The tutorial probably did not use FindGameObjectsWithTag
I'm pretty sure it only wants one LogicScript holder
not an arbitrary number of LogicScript holders
FindGameObjectWithTag returns a GameObject
FindGameObjectsWithTag returns a GameObject[]
ok
this helped
ty
also maybe can
its all about trying out
but do you understand why this worked, while the original code didn't?
my original code refers to multiple game objects while the code that I used to fix my problem refers to one game object?
Right.
The original code got an array of game objects, then tried to treat that like it was a single game object
so FindGameObjectsWithTag allows me to customise the number of game objects?
It lets you get many game objects at once
This would make sense if you could have many objects with the same tag, and needed to do something to all of them
kk
ok so if I used one tag on multiple things in my scene?
then findgameobjects would be used?
Right.
Hey all, sooo I have these serialized variables, where I can drag and drop the images that I want to use for the appearance of my playing card objects. However, I'd like to be able to change this image from any card and have the change be reflected across every card. I think "static" is my solution but I've never really been able to wrap my head around it. Could anyone help me out?
Change it in the Editor, or while the game runs?
Both ideally. I eventually want to have a in-game store for buying different card themes.
Scriptable objects can do that
If some cards are going to have different values than others then you cannot use static
Damn. Fair point. I'm already using an SO for card rank, value, and suit.
They wouldn't for appearance. These variables are just a reference point to pick out of. The actual applied sprite is treated independently.
But yeah I think this was an obvious one I just missed. I'll just move the variables over to the SO and then reference them in the appearance script.
Does anyone know how you reduce the loading scene time? I'm trying to create a casual mobile game using only 2d and the delay is quite noticable
Do you use LoadSceneAsync for this?
i have this code to enable a ragdoll when hit with an object tagged "hit" but i dont know what line of code i put here to do that, i have the enable ragdoll code (bit more code above off screen) its just the code to eneable it when hit with an object with the "hit" tag
LoadSceneAsync will not reduce the loading time. It will let you show a loading screen while it's happening though
Wdym by "hit"? Like a physics collision?
To detect physics collisions you use OnCollisionEnter/OnTriggerEnter depending on if you're using trigger colliders or not
yeah, i have a bullet object, and when it hits i want the model to ragdoll. the bullet has a tag called "hit" because i want to make other things be able to it like a throwable object. which i why i want to apply a tag to make it easier in the future.
^
I don't think a tag is particularly helpful here
I would say just make EnableRagdoll public, then the bullet script can call that function when it hits the player
wont that make anything i collides with turn it into a ragdoll then? for example touching the floor
or perhaps make a separate "Hit" function and call that (which then calls enableragdoll among other things)
no like I said
the bullet script would be calling it
Only if you tell it to
unless the floor has a bullet script for some reason
any way to reduce the load time then? seems weird there's this much time needed for a simple 2d game
I have no context for what "this much time" is in your case, but generally the answer is "load less stuff"
Your scene may be too bloated, and potentially you are loading too much stuff up front
perhaps you have things referenced in the scene that are rarely used that would be better off loaded on demand for example
it's hard to say without seeing what's in your scene and what is referenced from it, etc.
for example maybe you have some kind of menu for choosing different player skins and you have all the skins directly referenced in a script. This will cause them all to be loaded up front
In total there are only active 19 objects in the hierarchy (including children)
active gameobjects
sure but like I said any referenced assets are also loaded into memory
so number of gameobjects is only one part of the puzzle
so referencing a script increases load time as well?
if it's a script on a prefab asset, sure
any asset you reference is loaded
this includes materials. meshes, audio clips, video clips, prefabs, etc
hmmm so i sue OnCollisionEnter/OnTriggerEnter. and then go into my bullet script and make it trigger with the model to enable ragdol
basically I'm expecting this on the Bullet script:
void OnCollisionEnter(Collision c) {
if (c.collider.TryGetComponent(out Bear bear)) {
bear.EnableRagdoll();
}
}``` And that's pretty much it.
what is the collision and c.collider stand for?
yeah thats perfect! thanks a lot man, i was overthinking the code i think
Collision is an object that describes the collision
You get it as part of OnCollisionEnter
i have a player and an enemy. each has a rigid body and a collider. the player has kenematic flase enemy is try. yet when they pass each other the enemy pushes the player out the way. i want them to just pass though each other and not take force. what do i need to do
Use layer based collisions so they don't interact
https://docs.unity3d.com/Manual/LayerBasedCollision.html
can anyone help with how I can go about learning how to make other object follow one? like a trailer or even tail?
idk what to search for
Hello, i am brand new to unity and I have persisting issue across my projects and don't know what is going on
My camera is never showing my gameobjects in the game even thought it may in the preview
Are the objects actually in front of the camera
is it really so difficult to type
unity follow tutorial
into google?
i want it as a toggle its only as they pass when i rotate. i sent a video as an example its not all the time becuase i need to detect collision when they attack
i need to fill the bars for input and fuel cells, how do i do it? like make the bar on each cell fill over time (the amount of time it takes the fuel or input item to process)
https://hastebin.skyra.pw/ohosinesal.csharp
yeah. I've tried searching different terms but no luck haha. was thinking maybe i just didn't know what to search for
@polar acorn the camera is at z=-10 and my grid and player are both at z=0. doesn't that mean the objects are in front of the camera?
generally something like
bar.fillAmount = fuelAmount / maxFuelAmount;```
but im not even sure where that would go
Check it, rotate the view and see if they're inside the box that defines the camera
every time the fuel amount changes
like it has to be in update
yes
sure
Ideally you'd make a property so that when you set the fuel amount, it also updates the fill amount on the UI
So i've trying to make a cube to change colour when ever interact with it using the change cube color code in the minute 21:25 of this video https://youtu.be/gPPGnpV1Y1c?si=pqwMiFlRkQ0oSGce but he said it needs some setting up to make it work properly but i tried alot of ways to set it up but all of them didn't work
The second video in the Lets Make a First Person Game series!
🖐In this video we are going to setup the foundations for our interaction system.
Come Join us on the Discord!
🎮 https://discord.gg/xgKpxhEyzZ
💚 Thanks for watching!
Helpful Links
https://dotnettutorials.net/lesson/template-method-design-pattern/
e.g.
float _fuelAmount;
public float FuelAmount {
get => _fuelAmount;
set {
_fuelAmount = value;
fuelBar.fillAmounr = value / maxFuelAmount;
}
}```
so now whenever you set FuelAmount it happens automatically
oh. I misread. I didn't understand that you are not a good person. when i've already searched many term but haven't found what I needed
So what is the right way to set it up?
So many options
https://www.youtube.com/watch?v=FXOFinS9CeY
Follow in Unity - Fast Unity tutorial
#unity #programming
I appreciate the link. but i don't want to be chased by the thing. just want my train to have attatched cars
I'll continue searching
if you have train on some preset path like rails Im thinking sphere cast might be all you need 2 colliders at the "hands" where containers connect at and following container checks if it touches front one within distance if not slow/speed it up
I made mistake, but where. My spawner dont spawn block after 10 score. I use this two scripts. Can some help me?
https://paste.ofcode.org/mRrJ79fCp48B9aihKYatJ4
https://paste.ofcode.org/jScgBVpVKqZ7uvTxjKDdhm
Very confusing that you are doing
Debug.Log("A"); in BOTH places
that doesn't really help you figure out which code is running
you should have it print different things
but which thing? 🙂
anything you want
"Score is less than 10"
"Score is greater than or equal to 10"
that would be helpful
I exist people
your question was pretty vague though and required digging through a long tutorial.
a better way to ask the question would be to show the scene setup and code you tried and ask for help fixing it
ok, but its same only print A to 10, after 10 print nothing
not the same, no
that tells you much less.
Np
Js wait
cant rly spot ur issue but u can change this int randomIndex = Random.Range(0, leftGroupPrefabs.Length); for (int i = 0; i < leftGroupPrefabs.Length; i++) { if (randomIndex == i) { Instantiate(leftGroupPrefabs[i], spawnGroupPos, Quaternion.identity); } } into this int randomIndex = Random.Range(0, leftGroupPrefabs.Length); Instantiate(leftGroupPrefabs[randomIndex], spawnGroupPos, Quaternion.identity);
what error
int[] randomNumber = { 1, 2, 3, 4 };
int rN = Random.Range(0, randomNumber.Length);```
If you're expecting this to ever give you 4 as a result, you're mistaken
IDK what the point of the array is anyway
Search splines
Why not just:
int rN = Random.Range(1, 5); // will return a random number 1-4 inclusive``` and call it a day
real. mvp. thanks for the help!
you can also just replace:
if (rN == 1 || rN == 2 || rN == 3)
// and
if (rN == 4)```
with:
```cs
if (rN < 4)
// and
else```
this is the code: public class Keypad : Interactable
{
MeshRenderer mesh;
public Color[] colors;
public int colorindex;
// Start is called before the first frame update
void Start()
{
mesh = GetComponent<MeshRenderer>();
mesh.material.color = Color.red;
}
// this function is where we design the interaction
protected override void interact()
{
colorindex++;
if(colorindex > colors.Length - 1)
{
colorindex = 0;
}
mesh.material.color = colors[colorindex];
}
}
!code please
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Both of your colors have 0 alpha by the way., Not sure if that's intended
in what code or pic?
int he picture
0 alpha on both of these
anyway how / where are you calling Interact()? Have you made sure Interact() is actually running by using Debug.Log?
done it it done nothing
done what
i will now send the interact
seting them to zero
I didn't tell you to set them to zero
I'm asking why they are zero
that doesn't seem intentional
yes
Anyway you should do some basic debugging such as this
just for your knowledge the error is Null reference exception

i meant that isn't intentional
I'm having trouble finding attributes info in the docs, is there like a list somewhere? Maybe they aren't called attributes.. I'm referring to [Header("blah")], etc.
that would have been a really good thing to start with
sry mate
e.g. giving the full error message and indicating the line of code on which the error is happening
NullReferenceException: Object reference not set to an instance of an object
Playerinteract.Update () (at Assets/Scripts/playerscripts/Playerinteract.cs:36)
Expanding the Attributes thing in the docs will give you a list of all of them in the namespace
ok so show the Playerinteract script and especially line 36
Thank you
Notice it's telling you exactly where the error is @queen adder
Please post this to a paste site
Again, please share code as per !code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
At least we'll get line numbers there
yeah yeah sorry fellas just please wait
for the future. this is the beginner section so maybe everyone doesn't know certain terms. having people like yourself who don't even know what people are trying to ask, be angry for no reason really doesn't help anything. just like everyone else in this section. you don't know everything, humble yourself please
this is line 36 if(playerinput.Onfoot.Interact.triggered)
ok then playerinput is null
without seeing the code, i'd guess you simply never initialized it
never thought of that actually
how do i solve it?
initialize it
that's immediately the thought you should have when you see an error that says "NullReferenceException: Object reference not set to an instance of an object"
it's telling you you tried to use a null reference
im not good with english sry about that
how do i initialize it ?
Hard to say without seeing the code but likely something like this
void Awake() {
playerinput = new();
playerinput.Enable();
}```
if you want me to send it ill send
I wanted you to send the code 10 minutes ago.
something like this will likely sort you out
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
That makes three
Please format it like the bot says
this is wrong. delete this line: playerinput = GetComponent<PlayerInput>();
Your solution is here: #💻┃code-beginner message
Maybe they have their own PlayerInput, as per a very popular tutorial
Yes. That is clear by this line playerinput.Onfoot.Interact.triggered
I hate that tutorial
it manages to confuse the ever loving shit out of beginners every time by naming things in the worst way possible
In that case, it just means you just didn't attach that script aside Playerinteract on the same object
it's not a script that can be attached
it's not a component
it's the generated C# wrapper class for their input action asset
In that case GetComponent would have thrown an exception no?
It probably is throwing an exception
it is always useful to look for the first error
not just the error you're getting 400 copies of
the first error is often responsible for the rest
turning on "Collapse" can help with this.
done it and it gave me a new error
Don't keep me in suspense... just say what the error is
NullReferenceException: Object reference not set to an instance of an object
Playerinteract.Update () (at Assets/Scripts/playerscripts/Playerinteract.cs:27)
ok and which line is 27
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
And I guess that is FOUR times the bot was sent? Lol
Do not paste your code into the chat. Do not drag a file into Discord. Do not show us a single line of code. Share the entire thing with a paste site.
If you don't know how to do that, ask us.
Any paste site in here will do.
ok
My guess is private Playerui playerui; is null now
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

FIVE!
Is anything wrong with this code snippet? I have a sphere on the player set to trigger, i also refferenced the sphere collider. If a gameobject that has a tag "Enemy" + it has AIExample script on it, then it should call the OnAware function on that gameobject enemy, no? If i debug it it only runs twice on the false branch and thats it.
public void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Enemy"))
{
other.GetComponent<AIExample>().OnAware();
}
}
nothing wrong with the code per se.
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Click the link in the bot. Copy your code into that website. Click save. Copy the url. Past THE LINK here
SIX! SIX BOT POSTS! AH AH AH!
void start() You spelled Start wrong
Do not type ! code
ahuh now i get it
The Three Commandments of OnTriggerEnter:
- Thou Shalt have a 3D Collider on each object
- Thou Shalt tick
isTriggeron at least one of them - Thou Shalt have a 3D Rigidbody on at least one of them
No. They are typing it themselves. Thinking it formats the code
the problem is the OnAware function doesnt get fired.
no idea how you managed to have Start spelled correctly the first time and now you wrote start
bro waited someone to ask him for weeks now
No someone just thinks that typing the word that triggers the bot is what formats the code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
oh lmao
Stop. Typing. ! Code
Nope.
We only see an if condition testing for true
right that means that either OnTriggerEnter isn't running at all, or the object doesn't have the expected tag, or it doesn't have the expected AIExample component on it. Use Debug.Log to figure out which
You have to click save
If it has the Enemy tag, it gets the AiExample script regardless of whether it really has it or not, and executes the method. If you hit something tagged Enemy that does not have the script attached, you'll get an error
I have copy-paste macros of all combinations of these
i figured 😄
I believe you forgot to click save
Sometimes hatebin refuses to provide a link on save (browser extension block etc), if so try one of the other ones.
hatebin sometimes just doesn't generate a URL and we really should have removed it from the bot years ago
Oh good to know
nope clicked it
yeah it didn't generate a url
and for some reason everyone clicks that one first despite it not being the first
Use a different site
It has "hate" in it
It was popular several years ago
a powerful website for storing and sharing text and code snippets. completely free and open source.
And like most popular things on the internet became drastically worse as a result
finally
Does the object with this script on it also have a Playerui script on it
Okay, the problem was the enemy didnt had rigidbody. I was using NavMeshAgent, seems like it was sticking it to the surface then.
the playerui script is in the asset i might forgot to add it in the object
welp yes now i added it ill try
tried and nothing happend
welp thx to anyone who helped and sorry for being a pain in the ass but i am a beginner so yeah oc i would like that imma go get some sleep
and if you have a soultion leave it here ill read it when i get up
goodbye and good night or morning
Put a debug log inside the updatetext function. If it prints then this code is working and the issue is playerui
hmm.. new problem now. if the enemy gets aware it should move to the fpscontroller position (player pos):
if (isAware == true) { agent.SetDestination(fpsc.transform.position); }
however if i walk into the enemy i can push it and the awareness gets broken. this if is inside a update method. (when it didnt had rigidbody i couldnt push it, the enemy could push me btw)
What does "awareness gets broken" mean?
if i push the enemy it screw up the agent.SetDestination(fpsc.transform.position); code i think. correction if he touches me it also goes broken.
well, why not go from "you think" to "you know"?
I'd be logging inside that if statement, at the very least
to see if it's running
how do i make the fill amount go all the way to 1, and once its at one to lerp to the process time?cs foreach(FurnaceInputCells inputCell in inputCells) { if(inputCell.isProcessing) { float targetFillAmount = inputCell.processTime / inputCell.cell.item.GetProcess(ProcessTypes.ProcessType.Smelt).processTime; inputCell.bar.fillAmount = Mathf.Lerp(inputCell.bar.fillAmount, targetFillAmount, Time.deltaTime * 10); } else if(inputCell.bar.fillAmount > 0) { inputCell.bar.fillAmount = Mathf.Lerp(inputCell.bar.fillAmount, 0f, Time.deltaTime * 10); } }
you can see in the video it lerps to the process time straight away
and there is a little gap, it doesnt fill all the way up
Lerp is not a smoothing function
https://unity.huh.how/programming/specifics/lerp/wrong-lerp
how else do i do it then
Enter your start and end values, then increase the t parameter of the lerp from 0 to 1 over however long you want it to be
Then you could stop the coroutine
the inputCell.isProcessing sets to false
and then i need it to lerp back down
not filling all the way up is how its supposed to work while ur filling it back up processing is already going on
yeah i know
If you store your current progress, then all you need to do is increase or decrease that progress based on whatever factor, and the same lerp could be used for both
what do you mean
so set fill to max instantly when it ends or stop processing until it fills back if u want to keep animation. Or dont tie processing progress to lerping progress maybe get time needed from the item and use that to create a lerp
Hello I have this small code the goal of it is just to add x rectangle gameobject to a list of rectangle when I print the len of the list it show me the right result but when I print the content of it it seems to have "null" value I don't know why (I have the rest of the code but it's not usefull for that problem) ```csharp
using System.Collections.Generic;
using UnityEngine;
public class EntitySpawner : MonoBehaviour
{
private GameObject spawnedEntity;
private GameObject spawnedEntity2;
private List<GameObject> weaponsListDown = new List<GameObject>(); // Liste pour stocker les armes des anciens ennemies
private List<GameObject> weaponsList = new List<GameObject>(); // Liste pour stocker les armes
private List<int> weaponstypeList = new List<int>(); // Liste pour stocker les armes
private float spawnRange = 5.0f;
private bool entitySpawned = false;
private int life = 100;
float WeaponType = 2;
private void Awake()
{
for (int i = 0; i < 3; i++)
{
WeaponType = UnityEngine.Random.Range(1, 3);
if (WeaponType == 1)
{
weaponsList.Add(spawnedEntity2);
weaponstypeList.Add(1);
}
else
{
weaponsList.Add(spawnedEntity2);
weaponstypeList.Add(2);
}
}
UnityEngine.Debug.Log($"w {string.Join(", ", weaponsList)} {weaponsList.Count}");
}
}```
Where do you set spawnedEntity2?
I don't really do it
So, you are adding null to the list 3 times
I set swpanedentity like that ```csharp
spawnedEntity = Instantiate(entityPrefab, randomPosition, Quaternion.identity);
should I do the same ?
let me share the whole could would be easier for you to understand
here it is
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.
What do you want to add to the list
Okay and where do you reference rectangle
Okay where do you reference cylender
well I create my "main" cylinder like that ```csharp
private GameObject spawnedEntity;
// code code code
randomPosition = new Vector3(100, 0, 0);
spawnedEntity = Instantiate(entityPrefab, randomPosition, Quaternion.identity);
// code code```
but those 3 "line" basicly create generate position and display it
Okay, so is that the one you want to put in the list
yes same one
it's fine for me
So then add that to the list after you spawn it
like I add it when I press P ?
If that's when you want it to go into the list, sure
ok let me try it and tell you the outcome
wait what is the goal of my awake function then ?
I don't know what the goal is. I didn't write it.
That's something you should know
yeah I know dumb question
it worked well thanks
now I have another problem how can either hide my rectangle with pressing keynum9 and make it apear again when I press P or delete it when I press keynum9 and make a new one when I press P ?
Let me share the lastest code I have
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.
For the moment when I press key9 it dissapear well but when I press P again it don't reapear/create new one
you need a state machine
all these if statements in a giant Update function are confusing/convoluted
I should split the update function into smaller functions ?
how does that work ?
thanks
I just found a solution which isn't well coded at all but for what I have to do it's fine I just change the position to like 9999 on x y and z when I press 9
I know I should do better code but the problem is I don't have enough time for that right now
hi hi!
I'm currently working on a minigame and well I found a bug that you could still destroy objects even tho the time was over. Since the Spawn script and the ScoreSystem are two different scripts I've been trying to get a bool from the spawn script to my ScoreSystem. But when I tested it all I was left with the error
NullReferenceException: Object reference not set to an instance of an object
script1Reference = GetComponent<SpawnObjects>();
bool myBoolValue = script1Reference.SpawnIsActive();
Debug.Log(myBoolValue);
this is what I'm doing to get the bool from my spawner script. Anyone has any ideas on it?
script1Reference = GetComponent<SpawnObjects>(); this will only work if the two scripts are on the same GameObject
[SerializeField] SpawnObjects objectSpawner;```
The simple approach is to declare a field like this and assign it in the inspector via drag & drop. Then you can use `objectSpawner` as much as you want.
how can I access the file text of a file assigned to a UnityEngine.Object field..?
Why would you assign it to a UnityEngine.Object field?
Use TextAsset
[SerializeField] TextAsset myTextAsset;``` then you access the text via `myTextAset.text`
ahhhh I didn't think of thatttt. Yeah makes sense tho tysm
ah! that's what I was looking for
ty so much
so i have this raycast suspension script but theres only 1 problem, the raycast suspension has no friction. how would i add forward/sideways friction so i can go on sloped objects and not slide down it? heres the script https://hatebin.com/tklieorceg
friction is a force perpendicular to the surface and in the opposite direciton of motion
so you'd essentially calculate that perpendicular direction (using the surface normal from the raycast), and apply a friction force in the opposite direction of motion
you can basically project the rigidbody velocity on the plane defined by the surface normal and do AddForce in the opposite direction as that projection
so how would i get a rigidbodies lateral velocity? because as you stated i can just get this velocity and if its over a certain limit apply force in the opposite direction
you can basically project the rigidbody velocity on the plane defined by the surface normal
Vector3.Project will give you the part of a vector that aligns with a second vector
Vector3.ProjectOnPlane will give you the part that doesn't
thank you for the suggestion, ill read into it!
are you able to use collection literals with unity?
Is that a C# 12 feature? Unity is partially supporting C# 9
seems to be
yes, so you can't use anything from C#10 onwards
ok so i have a raycast coming out of a vehicle and when the vehicle crashes it executes a function but how would i make it so that if the object that the raycast is coming from crashes into something with the same tag as it it doesnt execute that code
"How would i make it so that if the object that the raycast is coming from crashes into something with the same tag as it it doesnt execute that code"
I'm having trouble parsing this. What do you want exactly? To check whether the raycast hits an object of the same tag?
just check if the hit object's tag equals your own tag
or call CompareTag with the other object's tag, I guess
let me try that
that didnt work
else if (hit.collider.tag == "winter" && dS.winterIslandConnected == false && hit.collider.tag == gameObject.tag)
its the last condition
else if?
Can you share whole code please?
gameObject but which game object has this script attached?
{
foreach (Light L in Lights)
{
L.color = Color.green;
}
gameManager.BroadcastMessage("AutumnConnect");
}
else if (hit.collider.tag == "desert" && dS.desertIslandConnected == false && hit.collider.tag == gameObject.tag)
{
gameManager.BroadcastMessage("desertConnect");
foreach (Light L in Lights)
{
L.color = Color.green;
}
}
else if (hit.collider.tag == "winter" && dS.winterIslandConnected == false && hit.collider.tag == gameObject.tag)
{
gameManager.BroadcastMessage("winterConnect");
foreach (Light L in Lights)
{
L.color = Color.green;
}
}``` it doesnt really matter about the other if statement but here u go anyway
its just the hit.collider.tag == gameObject.tag that needs fixing
@faint osprey
oh
the one with the ray cast coming out of it
Does the gameobject with that script have thr Autumn tag?
yep
Why the double check. If it does, then why check it explicitly AND via gameObject.tag?
Did you debug these 3 condition lines and you're sure the correct tags are appearing there? I'd assume the left side of boolean expression might be wrong? 
wdym
no cause they all worked before and then i added the last bit and its not working
You did:
hit.collider.tag == "Autumn"
And
hit.collider.tag == gameObject.tag
But if gameObject.tag is Autumn, those are the same
Then run the debugger and check what it detects at the place of hit.collider.tag
omg im an idiot its gotta be hit.collider.tag != gameObject.tag;
But you said the gameobject was tagged Autumn here
#💻┃code-beginner message
So it can't be != that AND == that
no im checking if the object hit has that tag to start with. then im checking if the gameobject hitting the object also has that tag
yeah it needed to be != instead of == at the end
Ok, then you just misunderstood what I was asking earlier. Nevermind them, not important anymore haha. Glad it works
{
aTubePos = aTube.transform;
}``` im calling this statement on start however when aTube gets destroyed later on in the scene im getting the transform ur trying to access no longer exists message
however havent i already got the transform data cause i did it at start?
the transform is a reference type
aTubePos = aTube.transform; just makes aTubePos point to the same transform as is on aTube
yeah
now do you care about the whole transform, or just the position?
since if just the position would store just that as a vector3
oh right
Hello, for part of my inventory system I found that it would be helpful to be able to select the type of item (class) from a scriptable object. Is there a way to have a dropdown menu of types in the inspector of an S.O.?
and what are you going to do with that type once selected?
you can easily build a popup menu and populate it with what ever you want, and can use the TypeCache or C#'s reflection features to get a list of types
but none of it really matters unless you know how you are going to use it
Keep in mind you're running that inside Start method, so you'll get only the starting position, if you want to keep aTubePos updated as long as the game object exists you probably should put that in Update() 
i dont i only want the starting pos
Alright then
then update the position each frame in update
or just hold reference to the transform and use it when you need to get position
though would null check it first each time
I had an idea, and after fully typing it out I just realized that it was a really roundabout and stupid way of doing things
. Sometimes its a good idea to put your idea on paper / say it out loud to see if its stupid. This was one of those times
Depends what data you want shown depending on the enum type
if it's all non-unique such it derives from another class, that's easily doable
but if you want to show/hide variables depending on the type selected, you need custom editor/attributes
im using a list to store GameObjects and im getting no errors in visual studio only in the editor which says 'aTubeHandler' does not contain a definition for 'instanObj' and no accessible extension method 'instanObj' accepting a first argument of type 'aTubeHandler' could be found (are you missing a using directive or an assembly reference?). any ideas?
exactly what it says it does not contain a instanObj or instanObj is not public
it is public and it does contain it tho
then you would have to show the problem and the related code
Basically I had a generic method for adding to an inventory that comprised of different lists (this sorted items by type when passed through). Each item has a reference to its own scriptable object which defines things like id, name, icon and description. I needed to pass something into the method to check type against, and thought that since the scriptable object was the item being added to inventory lists that it would make sense that it also contained type data. When in reality I can just pass in the item class (which already has a reference to the SO) and can be checked against.
yeah you already got the SO, so could just check what its type is later on
assumeing its a case where all items are extending from one type so they can be stored in 1 list, and you just need to figure out which spefecic one it is
i fixed it
yeah I literally just had to change the method call to refrence 'this' instead of 'itemSO' 🤦♂️
assuming this actually works
does foreach work with a list?
yes
{
Destroy(G);
}``` im getting problems with this then the objects arent being destroyed
for each works with any iterable (if thats a word?)
destroy is not instant it takes effect at end of frame
oh so if i spawn 1000 objects i have to wait 1000 frames?
no
your code would finish running before the end of the frame
1000 objects would get destroyed at the end of that frame
oh well thats not happening
there getting destroyed in the list but not in the game?
idk how
wait let me explain that better
i have a public list on the script
and when i look at the list in the editor all the objects get destroyed
however there still there visible in the scene
like i said confirm the objects in the list are the same ones in the scene that stay behind
what type is your list?
they are
wdym sorry
like is it a List<GameObject>
yeah
or list of some other script type?
its that one yeah
i think you are creating more objects then you added to the list
are the objects in the game the objects in your list?
yes
thats not possible
like i would not be supprised the ones in your list are not the objects in the scene
but are your prefabs
instanObj.Add(Instantiate(genTube, cylinder.transform.position, cylinder.transform.rotation));
thats how im adding the objects to the list
then like i said before adding logging and confirm you are destroying the objects you think you are
and that all the objects you want to destroy in the scene are in the list
there definitly the ones in the scene
try DestroyImmediate as a test?
you are going to need to do some debugging or show the code then
I'm trying to disable my starting camera and audio listener when i spawn in a new one as part of my multiplayer player prefab. here's my code:
var camera = GetComponentInChildren<Camera>();
camera.enabled = true;
camera.gameObject.GetComponent<AudioListener>().enabled = true;
Camera.main.gameObject.GetComponent<AudioListener>().enabled = false;
Camera.main.enabled = false;```
neither component is getting unchecked in the editor and i get log errors about two audio listeners. what am i doing wrong?
Are there other errors, and have you established that this code is running?
Because this camera is not tagged as MainCamera so Camera.main will not find it.
oh I thought Camera.main just grabbed the active camera and at the time the scene starts its the only one
its just grabs the ones with the tag
if multiple have the tag its not reliable which you get
just to double check application.quit() wont do anything when ur in the editor right
yep . . .
What would be the best way to check the type of item in this scenario? (where armor, weapons and genericInventory are each List<ItemSo> -- ItemSO being a type and not the var seen in the method)
Whats shown here doesnt work; but I feel its on the right path.
if(item.GetType() == typeof(Armor)) {
armor.Add(item.ItemSO);
}
else if (item.GetType() == typeof(Weapon)) {
weapons.Add(item.ItemSO);
}
else {
genericInventory.Add(item.ItemSO);
}
}```
for reference, this is my class structure: