#💻┃code-beginner
1 messages · Page 242 of 1
Ah shit yeah, my heads not in the right place for this lmao thanks
Is that possible to make UI in unity 2d by html / css?
Not exactly html and css, but ui toolkit/builder uses a similar language.
what im i supposed to do in this situation
Hello, I have a question about character jumping and movement, when i jump while running, it doesn't jump as high as when im not running or moving. Is this a frequent mistake in the code?
yes it's a mistake in your code
provide keystores or passwords in the publishing section of the project settings for your target platform
oh ok thanks
Then how can i keep the same jump height in my code?
Is there something to add or to remove?
You shouldnt be using 2 moves per frame with the cc, try to combine it to one. Also you really shouldnt move the position directly
Jump height could be a side effect of the 2 moves
I parented my character to a kinematic rigidbody moving platform in order for it to move with it. However, it is not moving with it normally. I change the rigidbody's position by setting its velocity. Does that cause a problem?
Uh the 2 moves?
Parenting isnt good for rigidbodies, because a child object will just be updated via its position. It has no respect to physics
The character controller .move
Oh i see
okay... then how do i make the character stick to the platform?
Doing it with rb is kinda tedious. You can try to apply the same velocity (from the platform) to the player but it might not work if the platform moves with rotation
If it's simple movement it should work fine
it doesn't move with rotation
If I have a nested Enum called ActionType in my PlayerController class, and I set the variable ActionType actionType using a method called SetActionType. If I wanted to call SetActionType in another script, would I use the line:
playerController.SetActionType(PlayerController.ActionType.Attack);
Yes
The best way to find out is to test it . . .
can u show me where that is
no because I don't have enough information. I don't even know which platform you're trying to publish for
android apk
I'm having a issue with prefabs, I'm not sure how to describe my issue so I attached a video (With text) below. Please help me if you can.
What component does the manager have?
If it doesn't have the block instantiator component, you'll not be able to drag it in
Also prefabs know nothing of the scene so they cannot reference scene objects
Oh
Hmmm, that may be the issue?
Is there anyway to fill those slots in my code, instead of having to drag the Block Instantiator into them?
Likely so. Any scene can be active at any given time. The prefab is always available though so having it reference a scene object makes little sense.
After you instantiate it during runtime, provide the appropriate references.
var instance = Instantiate(...);
instance.instantiator = this;//or whatever applicable```
What if I used GetComponent on Awake?
Why is this sometimes jumping three times the height? ```cs
if (jumpInputLetGo && isGrounded) {
rb.velocity = new Vector2(rb.velocity.x, instantJumpSpeed * multiplier * Time.deltaTime);
}```
It is sometimes a regular low jump (As I Want), but then sometimes it will jump three times that height. For context jumpInputLetGo is GetButtonUp for SpaceBar
my first guess is that multiplier might be getting altered somewhere
hard to say without the full context, though. you should do a copy paste in one of those "blocks of code" websites so we can see the whole script
multiplier is a const
Delta time can vary. Consider providing a fixed constant value if you aren't having to process something over time.
Should be fine as a means of acquiring a reference to itself (a component on it).
What do you mean by provide a fixed constant?
Remove Time.deltaTime
I just keep getting "An object reference is required for the non-static field, method, or property 'BlockInstantiator.SpawnRandomObject()'CS0120"
But I do seem to be referencing an object, the prefabs I think
Maybe show the code.
On that line you're trying to use the class name instead of the reference to access your method
I'm assuming you've got a static member trying to access a non static member.
using Unity.VisualScripting;
using UnityEngine;
public class FallingBlocksScript : MonoBehaviour
{
public GameObject BlockManagerObject;
public bool CanMove = true;
public float BlockFallDelay = 2.0f;
public float BlockFallDistance = 0.5f;
public bool TouchedGround;
private Coroutine fallingCoroutine;
BlockInstantiator BI;
// Start is called before the first frame update
void Start()
{
fallingCoroutine = StartCoroutine(FallRoutine());
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
CanMove = false;
Debug.Log("BlockTouchingGround");
StopCoroutine(fallingCoroutine);
TouchedGround = true;
}
}
void FixedUpdate()
{
if (TouchedGround == true)
{
TouchedGround = false;
BI.SpawnRandomObject();
}
}
IEnumerator FallRoutine()
{
while (CanMove)
{
yield return new WaitForSeconds(BlockFallDelay);
transform.Translate(0, -BlockFallDistance, 0, Space.World);
}
}
IEnumerator FrameTime()
{
yield return new WaitForSeconds(1.0f);
}
private void Awake()
{
BI = GetComponent<BlockInstantiator>();
CanMove = true;
TouchedGround = false;
}
}```
And
```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BlockInstantiator : MonoBehaviour
{
public static GameObject[] myObjects;
private BlockSpawnerScript BSScript;
// Start is called before the first frame update
void Start()
{
myObjects = Resources.LoadAll<GameObject>("Prefabs");
}
public void SpawnRandomObject()
{
int whichItem = Random.Range (0, 7);
GameObject myObj = Instantiate (myObjects [whichItem]) as GameObject;
myObj.transform.position = transform.position;
Debug.Log("Spawn Prefab");
}
}
your error message will have a filename and line number
what are they
Yep, it marks 39 in FallingBlocksScript
How can I destroy Player when it fell down?
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerController1 : MonoBehaviour
{
Vector2 moveInput;
// Start is called before the first frame update
void OnMove(InputValue value)
{
moveInput = value.Get<Vector2>();
Debug.Log(moveInput);
}
Rigidbody2D rig;
[SerializeField] float speed = 10f;
[SerializeField] float Jump = 10f;
BoxCollider2D col;
Animator anim;
void Start()
{
rig = GetComponent<Rigidbody2D>();
col = GetComponent<BoxCollider2D>();
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
Run();
Flip();
FallDead();
}
void Run()
{
rig.velocity = new Vector2(moveInput.x * speed, rig.velocity.y);
}
void Flip()
{
bool handmove = Mathf.Abs(rig.velocity.x) > Mathf.Epsilon;
anim.SetBool("IsRunning", handmove);
if (handmove)
{
transform.localScale = new Vector2(Mathf.Sign(rig.velocity.x), transform.localScale.y);
}
}
void OnJump(InputValue value)
{
if (value.isPressed && col.IsTouchingLayers(LayerMask.GetMask("Ground")))
{
rig.velocity = new Vector2(rig.velocity.x, Jump);
anim.SetBool("IsJumping", true);
}
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.collider.CompareTag("Ground"))
{
anim.SetBool("IsJumping", false);
}
}
public void FallDead()
{
if (col.CompareTag("Player"))
{
if (rig.velocity.y >= -100)
{
Destroy();
}
}
}
}
BI.SpawnRandomObject();
How to properly post !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.
did you save your code?
Yep
Can you show an image of the error - complete stacktrace
Like this?
The stacktrace would be the details pane when selected
this is a different error
https://gdl.space/udobapicaj.cs
Like this?
this is saying BI is null at runtime when you try to access it
the other error you showed was a compile error
Oh
Huh wait
One second
I think
Ugggh I think I showed the wrong error right before I changed something
Sorry
Also I'm not really sure where to find the details panel you are talking about
Destroy(col.gameObject);```
Is it a setting I may not have enabled?
No
When you click the error in the console window, it will show more information right there, also in the console window
Yep
Note to self, the strange box on the bottom of the errors console is called the stacktrace!
Interesting that it doesn't show more though
well it's actually just an expanded view of the full message, whatever that may be. In the case of an exception, that would show the full stack trace
Also, you're probably not wanting to destroy the player when it's velocity is greater than -100 but instead if it's velocity is less than -100. @raw sun
What is line 70
Destroy(col.GameObject);
gameObject not GameObject
So @ivory bobcat, do you think you know what my issue is
Its saying that line 39 is referencing an object without saying what object its trying to reference.
Which doesn't make much sense to me, because I tested the code that actually spawns the prefabs, and it works.
This is line 39
So its having some issues referencing the function or the script I guess.
BI.SpawnRandomObject();
Yeah
But is BI not set to BlockInstantiator?
BI is a reference variable. and it's not pointing at anything
at like 13
BlockInstantiatior is a class
that's just the type of the reference
Right...
Do you know what a reference is?
I think so
A reference is like a piece of paper with an address on it
That is a declaration, not an assignment
Declared but annasigned means null
Ah, miscounted. That's why posting longer code should be in links
if the reference is null, it means the paper is blank
when it's assigned properly, it has the address of an actual house
You are trying to assign it here: BI = GetComponent<BlockInstantiator>();
but GetComponent will return null if such a component doesn't exist on the object you're trying to get it from
which in this case is the same object this script is attached to
Is there a BlockInstantiator on the same object as this script?
No, because its attached to a empty game object which is meant to act as a manager of sorts
if not, you aren't assigning your reference properly
My issue is that I need to reference that manager game object
and I know how to do that
But it won't let me do that on prefabs
assign the reference after you spawn the thing
Is this the prefab that the block instantiator is spawning?>
you're making your life harder with the GmaeObject reference tbh
Yeah
Im trying to do it in code
And thats where we are now, me not understanding how to do that.
Usually always better to instantiate from a component than a gameobject
But you can do this:
GameObject myObj = Instantiate(myObjects[whichItem]);
if (myObj.TryGetComponent(out FallingBlocksScript fallingBlock)) {
fallingBlock.BI = this;
}```
(after making BI public)
AAAAHHHH
THAT DID IT
THANK YOU SO MUCH DUDE
Uh oh
Wait
Well it did work for a bit
Then all of the sudden it spawned in like a thousand prefabs lmao
sounds like an unrelated bug
Probably
maybe one of your prefabs has a block spawner on it
Indeed it does
Im tired lol
Well actually
None of them have the Block Insantiator script
This block spawning has plagued me for days 
Is the block falling script on the object instantiated?
BI is null because the component doesn't exist on this object
GetComponent returned null
is getcomponent bad? and should i start changing it as early as possible, or ok for starting?
I think I see the error
If this object is the instantiated object and the manager has the necessary component, after instantiating it with the manager set the public field to the manager in the manager script
And its really dumb (I think)
If It is null, i put !null in if statement I think, but not sure if ok here 
{
fallingCoroutine = StartCoroutine(FallRoutine()); //Here
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
CanMove = false;
Debug.Log("BlockTouchingGround");
StopCoroutine(fallingCoroutine); //Here
TouchedGround = true;
}
}```
Idk why I did this, but I believe I fixed it (changed StopCoroutine(fallingCoroutine); to StopCoroutine(FallRoutine());
It often leads to issues of NRE due to implicit requirements of needing the necessary components on the object to not be null. Other than that, there are some minor overhead.
Ahh, unfortunately that was not it...
Well actually it partially was
Im no longer getting errors
Its just spawning thousands of prefabs now
So much better...
As soon as one block collides with another, it all goes haywire, but when they just touch the ground, its all fine...
Uh oh
It won't let me back into my Unity window
I hope I didn't lose a lot of progress
I think i know what to do to stop a million blocks from spawning
for(int x = 0; x < size; x++)
{
for(int y = 0; y < size; y++)
{
GameObject gu = GameObject.Instantiate(
gridUnit
,new Vector3(x/1.5f, y/1.5f, 0)
,Quaternion.identity
,GameObject.Find("Lobby").transform);
}
}
so this script i create quickly for testing and the result is in attachment. Basically it create a grid of squares in x and y and I want to make the 100x100 squares contact perfectly without overlap
but when i dont divide by 1.5, I get the spacing in the grid. Why is that?
I am getting an error saying: The variable audioSource of SoundManager has not been assigned.
You probably need to assign the audioSource variable of the SoundManager script in the inspector.
SoundManager.Start () (at Assets/SoundEffectsCoin.cs:11).
I am trying to add a sound effect on an object, but when I play the game, it is not there
maybe it is positioned in x and y, then divide by 1.5, which is why it gets smaller if different number? (x/1.5f, y/1.5f, 0). it is in x and y
It says you didn't assign a sound in the inspector
Yeah, that is what I have been told. I did
I added the sound effect on Audio Clip and also created a script with it. I guess it is a script issue
Show us what's on line 11 in SoundEffectsCoin.cs
thank, i guess that makes sense. I found it hard to wrap around my head that this also is the spacing when x and y both go up from 0 1 2 3 4 regardless of 1.5 or not
bevause i set size var to 4 and doesnt change during runtiem
ah, hmm
but i dont know how to fix
Where do you assign boingSound ?
perhap something like using spacingX and spacingY will make that mroe clear for me instead of explicit value
more
int size = 10; // Number of grid units in each dimension
for(int x = 0; x < size; x++)
{
for(int y = 0; y < size; y++)
{
float offsetX = (gridSize / size) * x;
float offsetY = (gridSize / size) * y;
GameObject gu = GameObject.Instantiate(
gridUnit,
new Vector3(offsetX, offsetY, 0),
Quaternion.identity,
GameObject.Find("Lobby").transform
);
}
}``` can you try this, ah but not sure if working xD
I'm not sure where to assign it. I wanted to assign a wav file on the script. sfx-boing.wav , spefically
thank! maybe also it just a code clarity issue .. that looks like a good way to write it
You assign it in the Unity inspector
If you find anything about the code, tell me ok
I want to learn it also
How do I find Unity inspector?
Ugghh
It's the same window where you have assigned SoundManager script
So from what it looks like, it is already opened
Send us a screenshot of your inspector
You can see audio source is not assigned
Do I add that sound to Audio source instead or do I set it to both Audio Source and Boing Sound?
your script works, thank! i tested it and adjusted the offset and the tiles outputted really nicely
this probably useful if someone making a word search or something
public static void AlphaChange(this SpriteRenderer sr, float alpha)
{
var col = sr.color;
col.a = alpha;
sr.color = col;
}```is there better way to do this?
Is there a problem with this method?
not really just hoping theres a better way :3
ah, I dont what it means
I havent tried sprite renderer
if it ain't broke..
So I was able to assign it to coin, but I am still not getting any sound effects from it
most likely because your AS not playing the clip, you need to do cs AS.PlayOneShot(AC);
Where do I add this? In the script? Which line?
in the play line
change the play cause it just play whatever is in the audiosource (which i think is currently empty)
im firing off projectiles using a weapon script, it's fired off using an input (mouse 1), im trying to create a turret like assist for the player that will also fire off when they are firing, using the same function that the weapon uses to fire. the function takes a transform parameter so it knows where to spawn the projectiles, the issue im having is only one is ever firing at one time, when I want both of them to fire together, they are currently both running the function off the mouse 1 input
Share code
What's WeaponManager.CurrentWeapon? Where's the code from each screenshot for?
It's very confusing. Please use the !code sharing guidelines and share the whole scripts:
📃 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.
<@&502884371011731486>
Could anyone help me with this?
You probably dont want to be using collision messages for this, because of this issue. How are these objects moving? Is it on a grid like tetris
Yep
Hello
Can you please help me with RigidBody.AddForce?
For some reason it doesn't move my object whatsoever.
It doesn't give out any script issues - it just doesn't move
transfrom.Rotate work tho
Rigidbody playerRb;
public float verticalInput;
// Start is called before the first frame update
void Start()
{
playerRb = GetComponent<Rigidbody>();
gameManager = GameObject.Find("GameManager").GetComponent<CampaignGameManager>();
}
// Update is called once per frame
void Update()
{
Movement();
}
private void Movement()
{
verticalInput = Input.GetAxis("Vertical");
playerRb.AddForce(transform.forward * verticalInput * speed * Time.deltaTime);
float horizontalInput = Input.GetAxis("Horizontal");
transform.Rotate(Vector3.up * horizontalInput * rotateSpeed * Time.deltaTime);
}
Down 0.5 Units every 2 seconds
- Don't multiply forces by deltatime
- Check the value of
speed - Forces should be applied in FixedUpdate
- If you use
transform.Rotateit'll mess up the physics collisions
It worked
Thank 🙂
Hi do all components have reference to its gameobject and transform (like when we say this.gameobject or this.transform) or do they call getcomponent<>() behind ?
youll probably want to introduce some custom collision detection then, although sorry ive never made such a game i cant really suggest much. simplest way would likely just be checking the positions an object is moving to. assuming the grid data is stored in some array
accessing the transform doesnt use get component, and also the game object is not a component so that one doesnt really make sense
cool! thanks
using UnityEngine;
namespace GenshinImpactMovementSystem
{
public class Player : MonoBehaviour
{
private PlayerMovementStateMachine movementStateMachine;
private void Awake()
{
movementStateMachine = new PlayerMovementStateMachine();
}
private void Start()
{
movementStateMachine.ChangeState (movementStateMachine.IdlingState)();
}
private void Update()
{
movementStateMachine.HandleInput();
movementStateMachine.Update();
}
private void FixedUpdate()
{
movementStateMachine.PhysicsUpdate();
}
}
}
Its giving me an error CS1503 any fixes?
dont cross post
Nobody remembers error codes, show the full error and the line it points to @ashen adder
Hey, I have a FSM Manager with a function NextState(); that invokes the method dinamically based of the current state using Reflection. How can I make it so that NextState() Invokes coroutines in other files? Here's the code: https://pastebin.com/UP0w42Wn
🤔 why do you need reflection here in the first place? is this AI work
iirc I got the script from a video which could have been ai
ditch the script, this is garbage
dear lord i just looked closer at what the reflection is doing, using the enum state name then adding StateStart to it 
use an abstract class for your state, then each child class (the actual states) will override a StateStart method. This way you can call any StateStart method without all this fluff
or use interface, though abstract class is much better
Thanks, I'll look into that, I remember trying to do something like that before
I barely knew the first thing about programming so I ditched the idea when trying to figure out what abstract meant lol
to answer your question also, yes you can start a coroutine on another class. It will be much easier to do when you have the actual instance of the State
But I have the state files in a game object and a reference to them, isn't that an isntance?
like this?
yes
the fields you have
public WalkState walkState;
public CrawlState crawlState;
public DieState dieState;
are where you would store the actual instance. except the type would just be of the abstract class (or interface) like
State whateverNameHere
!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.
The space button isn't working as a jump in my code, but the WASD keys are working just fine?
Doesn't seem to be a coding problem from what I can tell so not sure why its not working.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterControl : MonoBehaviour
{
public CharacterController controller;
public float speed = 1f;
private Vector3 playerVelocity;
private bool groundedPlayer;
public float jumpHeight = 1.0f;
private float gravityValue = -9.81f;
void Update()
{
groundedPlayer = controller.isGrounded;
if (groundedPlayer && playerVelocity.y < 0)
{
playerVelocity.y = 0f;
}
Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
controller.Move(move * Time.deltaTime * speed);
if(move !=Vector3.zero)
{
controller.gameObject.transform.forward = move;
}
// Changes the height position of the player..
if (Input.GetButtonDown("Jump") && groundedPlayer)
{
playerVelocity.y += Mathf.Sqrt(jumpHeight * -3.0f * gravityValue);
Debug.Log("Jumping");
}
playerVelocity.y += gravityValue * Time.deltaTime;
controller.Move(playerVelocity * Time.deltaTime);
}
}
Do you get the log message?
nope
I only get it when i can visually see the jump which is extremely few and far between
so hypothetically it works but not all the time, so I'm not quite sure what's preventing it from doing so all the time
Probably the ground check then. Try removing it from the condition, if it works consistently after that then that's it
that works, but i don't want double jump enabled.. is there any workaround?
That wasn't meant to be a fix, you have to first identify the problem before you can fix it
now figure out why the ground check doesn't work and fix that part
I don't use the CC but check that you don't have any extra colliders etc
If your IDE is not underlining errors in red you need to configure it. !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
• Other/None
I'm using some code to get the difficulty of the game using a little formula (infinite mobile game). For some reason, it is returning NaN.
difficulty = ((1/200)*Mathf.Pow(numSpawns - 70, 2.2f)) + 100;
Where numSpawns is how many times the 'enemies' have spawned.
Wdym?
Exactly what I said. Read the bot message.
So all I have to do is just download one of those?
Are you sure you're getting the error on this line? Can you assign the Pow part to a local variable and debug the value?
No, you need to follow the instructions relating to the one you have installed.
Okay thanks!
numSpawns is less than 70
That would make sense, but when using the same formula on Desmos I get a continuous graph with no gaps
ie it's always defined
Is there a quirk with unity where you can't use powers with negative numbers?
Good for Desmos, but Mathf.Pow expects a positive value there
I don't think that's correct. It just raises the first param to the power
this is math problem, non integer power of negative returns complex number
Yea issue is with the float
You can't raise a negative value to a fractional power
Ah I didn't know about that
Any idea how I could get the same graph without sitting around playing with desmos for another hour
A fraction is kinda like getting a root, and you can't get a root of a negative number.
I think
Yep that's right
Is it critical to be able to evaluate x < 70?
I think I could just play with desmos for a bit and find a similar looking equation
the exact same graph or just something similar? looks like a stretched cubic function
Yep, pretty much that
I'll play around to find something similar
just replace the 2.2 with 3 then and mess around with the 1/200 then
Yep
although it will get drastically different if you are using large numbers
In the near impossible case someone gets that far
I'll just let it be linear at some point
Can't you use an animation curve instead of hardcoded math?
Never thought about that, I've never used an animated curve
Wouldn't that just be related to time, not how far the player has gotten?
do the animation curves let you extrapolate? i assumed you could only use it for a curve that you define values for and not an infinitely reaching curve
I'll just stick to hardcoded math
Far easier for my small brain
And it's a very small game so it won't be something that bothers me later down the line
Even if it does, wouldn't be hard to switch systems
Beyond the defined values, it would extrapolate linearly I think.
I never codded in c# or any other language should I start with a less complicated language?
C# is no more nor less complicated than any other language. Take a look at this
https://dotnet.microsoft.com/en-us/learn/csharp
theres no reason to really start in a "simpler language" which really just means python. I notice people who start with python often have difficulties transitioning to another language because of how unique it is.
I started in c# (if we can exclude my year of VB winforms 😄) and Im still glad my teacher taught c# first
Yo guys, how do i get the range of two numbers in unity?
Python
for example: 200 - 50 = 150
150 is the range between the numbers 200 and 50.
do you know what subtraction is?
int x = a - b;
I'm so confused... didn't you just answer your own question?
You just answered your own question
no
because theres an issue
Post the code then
the code wont check if the number is like say 200 - 300
it will return a negative
which is not what i want
get the absolute value of the number then (google how)
then you want Math.Abs
Mathf.Abs(x - y)?
Write an if statement to check which number is bigger
Or use one of the many methods that already do that
would that give me the same result
Or you can just be lazy and convert the negative number to a positive one
or will it be an incorrect distance?
it gives you the Absolute (i.e. positive) value of the subtraction
how do I get the verticies of the terrain to change the positions of the grass accordingly else this happens. any solutions ? Currently I am using constant Y axis value and random X and Z. with gpu instancing.
oh thank you!
I hope you're not gonna sample it every frame😬
at start only
what kind of grass is this? particles? gameobjects?
Mesh
billboard ones
so gameobjects?
kind of yes
wdym by "kind of"?
idk if Its gameObject caues I am not using Instantiate(); I am using Graphics.RenderMeshInstanced();
so its not gameobjects
yes
anyway, by this method there is no shortcut, so everything is said... had it been particles you could have referenced the terrain data and have it sampled via vfx graph.
One more question is there a way I can get the Terrain Layer / Texture at a point in the terrain to remove the grass from the sand part ?
how do i do a .getComponent to get an image
like i want to get that Image comonent
do you have a reference to the gameobject or is the script on this gameobject?
This allows you to sample the splatmap(s) https://docs.unity3d.com/ScriptReference/TerrainData.GetAlphamapTexture.html, you have to calculate the UV coordinates you want to sample yourself afaik. Overall this should give you access to all the data you need https://docs.unity3d.com/ScriptReference/TerrainData.html
Is there a way to change the color or alpha of a 'Tile'?
public Tile tile;
please read the docs
https://docs.unity3d.com/ScriptReference/Tilemaps.Tile.html
I tried this earlier and it was t working. I found a solution that I have to
use TileMap and give it the position of the tile, set its color flag, and then
use the TileMap give it the position of the tile and give it a color
I’ll see if I can change the color directly referencing the Tile. Thank you.
i have a reference
then it's simply
Image image = refToGo.GetComponent<Image<>();
like any other GetComponent.
just make sure you have the correct using statement for the Image class
is there a way to highlight specificmesh rendererer but without creating instanced materials (without highlighting meshes that use the same shared material)? maybe with resource blocks.. the reason i dont want instanced mats is because i usually keep forgetting to replace them with sharedmats when im done highlighting but maybe ill just need to do that
You can swap the renderer's sharedMaterials array. This will not instantiate materials, while materials does
I mean change to a completely different material while highlighted
using System;
using UnityEngine;
[Serializable]
public class flashlight : MonoBehaviour
{
public GameObject flashlights;
public AudioClip switchsound;
public Light myLight;
public flashlight()
{
myLight = (Light)flashlight.GetComponent("Light");
}
public virtual void Update()
{
if (Input.GetKeyDown("f"))
{
myLight.enabled = !myLight.enabled;
GetComponent<AudioSource>().PlayOneShot(switchsound);
}
if (Input.GetMouseButtonDown(1))
{
myLight.enabled = !myLight.enabled;
GetComponent<AudioSource>().PlayOneShot(switchsound);
}
}
public virtual void Main()
{
}
}
myLight = flashlights.GetComponent<Light>();
flashlight is a Method. flashlights is the GameObject
anyone made a grid checkbox system before? Like ruletiles, but probably larger
for tilebased movement something
like this
in inspector, is it hard?
probs just a simple answer but im making like a vinyl player and its as simple as making an event for each like "disc" that activates music when played ye?
There is GUILayout.SelectionGrid, but you probably meed multiple selections at once?
You could just draw a bunch of buttons tbh
Or toggles with button style
can information be saved to an SO?
it's for movement of pieces thingy
Only in the editor really
uh so i cant use it?
If you need to save the SO in a built game, then no
What exactly do you need to save?
i mean i just need to tell that my archers can attack in the square 2 box away from center
then lancers can attack in a + shape
Ok but does that change during gameplay?
But those included in the build are immutable (or rather, not gonna persist through the sessions)
no
You mentioned saving so I thought you wanna change the SO while playing
Then its ok. You can read from the SOin a built game
And yeah can make instances of SO too if needed
5 rows of 5 toggles
thx! :D
hey guys where do i go to for help with scripting camera movements? i dont want to be in the wrong place
GUILayout.Begin/EndHorizontal for each row, GUILayout.Toggle for the buttons
Can use the string "Button" as the guistyle parameter in Toggle
thanks imma look for them
here, post your question and your !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.
So it looks like a button and not a radio button
ok so i have never used unity before and for an assessment i have to make a rollaball type game. i want to make the camera follow the player (a ball) but when i find a script online and use it, it doesn't work as i need it to work. i tried using ai to fix it up but it doesn't do it properly. been trying for the last two hours but couldn't figure anything out so i came here. i also installed something called Cinamachine and tried to use that but couldn't figure out how to do it properly.
my code https://hastebin.com/share/qerivofice.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
we do not provide support for AI Code on this server but reading your question I think you need to spend some time learning Unity. !learn is the best place to start
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Assessment? School assignment or what?
Why are you tasked with it with 0 experience with unity?
bro its the teachers that expect us to know all this stuff
Didn't they teach you or at least give you time to learn it yourself?
nope
That sounds very fishy. I'd complain to the school administration for giving unreasonable assignments
they wont do anything
That being said, I'm afraid we can't give you a complete solution. You'll need to learn and come back with specific questions, details on the issue and explanation of debugging attempts. Check #854851968446365696 for more on how to ask a question more effectively.
so what if i say i have a problem with my script. i wrote a script to follow the movement of a ball that rolls around but for some reason it wont follow properly. I have tried searching online for other people doing the same im doing but cant find it. here is my script https://hastebin.com/share/qerivofice.csharp
any thing i can do to fix this issue?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
are their any other servers that help with unity stuff?
problem is, it is very obvious that not only did you not write this script, you do not understand it either
i can kinda understand it
first getting services then defining what stuff is then the main stuff
Assuming, you have everything setup correctly in the inspector, I'd assume the issue is with incorrect lerping.
yeah the target is Player1 height offest 3 and follow smoothness 0.1
what should the lerp be?
wait
dont tell me
i'll figure it out myself
Check the docs for how to properly use lerp.
Realistically, forget it, aint gonna work
is there a cleaner way to do this ?
Vector3 moveDistanceV3 = new Vector3(
raycastHit.point.x - player.transform.position.x,
0,
raycastHit.point.z - player.transform.position.z
);
because Unity does not support Python code
Vector3 moveDistanceV3 = raycastHit.point - player.transform.position;
moveDistanceV3.y = 0;
Whether that's cleaner is a matter of opinion
pretty sure there are websites that can do basic Python -> C# translation
Hello there. How badly do Coroutines/IENumerators suck compared to async and how badly should I be willing to learn how to use async?
that's like comparing chalk and cheese, both have their place and time
ohh... okaay. So async isn't like better better coroutine, right? I mean... coroutines aren't deprecated just because async exists?
no, not at all, they are two completely different concepts
got you, thanks a bunch!
better has some subjectivity but they share a lot of similarities, the concepts are closely related, and the implementation is closely related. In Unity they are both typically used to solve the problem of time splicing & concurrency, though tasks with async/await are much more powerful (but come with some extra complexities because of that)
In Unity you can get away with never understanding it and just fiddling with coroutines, in the "real world" outside of Unity it's a fundamental concept of C# and other languages, so I'd definitely recommend learning it
thank you
Hi together. I tried something with the unity job system and have some questions. What is the correct channel for that? general or advanced or beginner? (i think it is more of a beginner question but related to the job system)
Still an Advanced topic imo
Hello, i have a question about the camera and body movement, when i move the camera, the entire body moves to face where the camera is looking. Is there a way to move the camera without moving the body?
that depends on your heirarchy setup and your code
That's basically it
So there is nothing in your code that directly references your Camera object. All I see is Controller.Move which, I presume, is a CharacterController attached to your player which will, of course, affect all children objects of that Player
Oh i see so i have to either move the camera out of the player or put something in the script that manages the camera
exactly, think about it, if you are sitting in a car and the car moves, do you move as well?
Ooh yeah i see
Loop through the array, check each element's y-axis, and assign the target variable to the current element if its value is less than the current target's y-value. The one assigned at the end of the loop will have the lowest y value . . .
In this case, there is no such thing as better or worse, it all depends on what best fits the mechanics you want to implement
There is no general answer, as it depends on the type of game and movement you want. One can make the same game with both types of controllers . . .
Then is RigidBody harder to implement?
I tried using RigidBody on Godot once, i got traumatised
you miss the point, you would not implement Pong without Rigidbody and also you would not implement Tetris using rigidbody
I have no idea the difference between Godot Rigidbody and Unity's version. I'd test movement with both controllers and decide which one feels/fits your gameplay better . . .
Question about when to use events/delegates vs references/polling. Object A changes its color based on Object B's state. Currently, A has a reference to B, and it checks B's state in Update and sets its color accordingly. Is there a point at which I should be concerned about this, performance-wise?
Or is it more of a best practices thing, where it's better to decouple things and use delegates for cleanliness?
It probably won't be a noticeable performance thing unless you're doing this across thousands of objects. It's more of a cleanliness thing yeah. If you suspect that the colour changes rarely, or based on something that isn't Update frequent, then you can just subscribe to an event on that object.
an event will do nothing to decouple things here
But I would still use an event instead of Update for this
Object A will still reference B, in order to subscribe to the event
B will fire the event, without an explicit reference to A
So nothing changes about the dependency graph
(Unless you make it a static event that passes itself but that really depends on your setup)
I'm just a few days into even understanding events, so I wouldn't know how to implement that
It's probably not what you need, anyway. Keep with what you're doing
imported Book of The Dead in a blank HDRP project and here's an error i got
And the lines of code causing the errors?
those codes and files came within the original asset
so, show what they are, they were probably made for a different version of Unity and may no longer work
how is that supposed to help? Use some common sense please
what do you want?
the 2 lines of code that are throwing the errors
Double click the error message to go right to the problem code
am literally a beginner and i have no idea where and how those are
already doing it
read the error messages, they tell you exactly what and where
i am not a coder, i do not know how to exactly fix them
do you want me to paste the codes in here?
I want you to show me exactly those 2 lines of code mentioned in the error messages
ok, lemme try finding them
this is the code file, the line number is 19. Do you understand this?
yes
stupid question but is there anyway I can keep a frame by frame animation, but change character armor/helmet/boots/gauntlet?
something like a composite sprite where I only use the "naked" character and put layers of clothing on top of the animation through code?
Yes, just animate the sprites individually and change the sprite on the SpriteRenderer. As long as the animation is only moving things, you can put whatever sprite you want at runtime on the component.
mind if I message you directly? completely new to unity and im trying to understand this more
Or, if you want to animate only a nude character, you can use code to snap a separate sprite object to it.
I don't do DMs, sorry
all good i guess ill just ask here then.
this one, i think this is closer to what i have in mind
so I have to make the objects/sprites as a completely different thing right? i wont merge them to the old nude character sprite like on this vid? https://www.youtube.com/watch?v=tdTfgo9_hd8
in this tutorial we look at how we can grab multiple sprites and combine them into a single one! this is great if you need to export the combined sprite for whatever reason. just a tiny tutorial that might be useful to some! :)
Socials!
🐦: https://twitter.com/PhillTalksAbout
📸: https://www.instagram.com/lucernaframeworks/
🏠: https://phillse...
basically what I have in mind, is banner saga's smooth 2d animation but I can change the character's clothing
The way you could organize it is have a character made up of multiple child object containers (head, body, arm_left) and animate those containers.
As a child of those container is the actual body sprite (nude) so that it follows.
As another child of those containers, and on a sprite rendering order higher than the body part is the clothing piece (so it appears on top).
That's exactly what I do for my RPG^^^
MyCharacter (root object you actually move around with code)
> Sprite (contains animator)
> Head Container
> Head Sprite (nude) | spritegroup: Character, order 0
> Head Clothing | spritegroup: Character, order 1
> Body Container
> etc.
It seems like the guy ur watching is over complicating it IMO balforth
You just need to make child gameobjects for each customizable part of ur character and change there sprites at runtime.
let me try and visualize this from what im getting from you guys
Another vague-ish best practices question. If a script will for sure only ever have or need a single instance, is there a good reason not to implement the singleton pattern for it?
Nope, use a singleton and make your life easy
For example, managers or even the player in a non-multiplayer game are great singleton candidates
I also use them on canvases in a root scene. GameplayCanvas, DialogueCanvas, etc.
Yeah these are canvas/UI scripts I'm working with here. Mkay, thank you
Will other scripts actually need to reference that single instance?
Ah, nevermind
@queen adder @frosty hound like so?
As a follow-up, any reason not to make all member variables/methods static? So that I can just access a function as MySingletonUIScript.ButtonState as opposed to MySingletonUIScript.Instance.ButtonState
Or more so on type of the nude body
and I can still create separate animations for those individual sprites right? like moving clothing etc
Yuh^^^
how would I determine the clothing layers tho? or will whichever comes first on the code be the one at the top?
SpriteRender.Layer
You can change that via the unity editor inspector. Higher layer means it appears on type of anything with a lower layer number
Anything that's static you can't access via the unity inspector other than that I think it's fine
ill do a test when i've finished the animation for the idle animation and see if I can swap around the clothing
thanks for the help 😄
I tend to lean more towards static events for my UI or just have my UI listen for everything else
Okay, sorta back to my earlier question from before... I recognize that I'm very much in the weeds right now and won't notice any differences between the two implementations, but I'm just wanting to get some best practices in place.
Say object A has an enum state, and a color changes based on the state. The state and color are both members of object A. Is it better to check if the state has changed and then use a switch statement to change the color, or am I fine just skipping the state change check and setting my color in every Update loop (though it will almost never be changed for any given loop)
static members only exist on the class and not each individual instance. that's a big difference. also, they do not appear from the inspector . . .
If objects A's color changes state and the state determines the color... then yeah just a normal switch statement is fine? It doesn't have to be in update? Who's changing object A's state and how?
anyone know a fix to this?
How the state changes isn't relevant I don't think. It's more a question of whether I should only update the color at a state change or if I can set it every Update.
But yeah I get your point that I can just tie the color change to the state change.
How the state changes is relevant for sure. If ur just accessing the enum field I would have some sort of get and set that also changes the color when accessing the field
I typically have a method just called ChangeState() and when a state changes for a specific class I raise an event or update the rest of the class some how
Hi guys, I want to ask what does the "?" in the code do?
A different script has the error
Null check
Which one would it be?
ok this is kinda weird
Look at the error it tells you
You can also double click it and it will take you to it
why does ontriggerstay only activate while the player is moving
Yeah thats what I did and it sent me to line 26 on that script
i have a series of weapon pickups, and theyre only detected when collided with
Is it 2d?
yep
Oh I'm stupid
The error shouldn't be on line 26 it looks like Line 16 is ur problem
What would the problem be?
Ur passing in the wrong type
Sorry Im really new to this what do you mean?
The method ur calling
MovementStateMachine.ChangeState()
Doesn't take movementState.IdleState as a argument
Also ()(); is invalid syntax
!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
• Other/None
So what should I change it to?
Show me ur current code please
It's saying the argument should be of type GenshinImpactMovementSystem.IState
Is the PlayerStateMachine supposed to inheret from IState?
Yeah
Could you share the code for that?
Actually my mistake it shouldnt
Are you following a tutorial?
Then it should not go in that function
That function expects IState
Yeah lol
That's why I'm asking because you said yes then said no so I'm guessing you rewatchd a video
It's supposed to inherit from IState for sure
this is oddly satisfying
Do you use animators or blend trees or just use script for handling animations
i tried to modify the rotation parameter in the shader graph but it doesnt work?
the name is wrong
click on Rotation here
then look in...was it the Graph Inspector or the other one?
Reference name?
ah i see thank
so, in your case, it's probably _Rotation
The default is to add a leading _ and to replace spaces with _
"Total Damage" becomes _Total_Damage
i see i see
I saw a guy on YouTube saying that, stop making webs on animators and instead use this, he showed that
animator.Play("")
thing to handle animations
Well, should I use this for 3D games and movements ??
personally i use blend tree's when i can
if its a simple state/machine type anim setup i use code
I think it's a good idea for situations where you unconditionally play an animation
okay... specialists of unity, I like to organize some of my components in diferent objects, like, a object specific for visuals, and a object specific for sound inside the main object, but many of them are empty, how much does a big amount of empty game objects can affect my game?
Or for when the conditions for the animation are hard to express in the animator controller's state machine
everything has a cost but its prob too small for you to notice
Okay
but if like... we are talking about the fact that I need up to 100 of those things spawning?
As long as u dont plan for a mobile release it's probably fine
What do you consider a big amount? Like a thousand?
100 is nothing
Eh. Should be fine
Can we make blends between animations with scripts like the animator one?
Animator.Play() is fine but you lose transition options and visual scripting which is what Animator is really for. But for a simple game it's fine
Hmm ok
Well, is it good to make movement and animation controllers in one script ?
I would personally sperate them
As long as they're not being moved or their position is being updated individually, you're fine . . .
Okay then
And makes the classes harder to read and understand IMO
I'm separating them too
That might be fine. But then you might end up with animation being handled in the movement script, AND an attacking script, AND some interacting script, AND AND AND.
Best to separate as much as you can
most of them have audiosources, and are moving as Sons of the main one
but not individualy
but the audio sources would stay, I just don't wanna have all of them in the same object
Gets kinda confuzing to find a specific audio
Keep them separate. Movement is not the same as animation . . .
is there a way to prevent rigidbodies from merging child colliders with self?
i have a rigidbody with a collider, and I want a bigger collider to use as a raycast target but also want to use the main collider for physics
layers
There's two ways you could do it off the top of my head
Layers or Physics.IgnoreCollision()
Is there a way to ignore collision with all colliders at once?
Seems like it works by pair?
Layers then
They are already on layers, what's the next step?
Not quite sure what that means
idk why the goggles and abckpack just acting weird , last time i did this , it was working fine but idk why the goggles and backpack seem to rotate ig? idk it seems weird
https://paste.ofcode.org/s8psarVmq9te9gQHHzcSWR , moveCamera script
Put them on separate Collision layers
oh COLLISION layers, hmm
And inside the Inspector you can tell them what collisions to ignore via the Collider2D component
https://youtu.be/f473C43s8nE?si=dsqEdurxnVwMR5xQ i was just following this tutorial , i did it before and it was working fine but now they jsut actting weird af
FIRST PERSON MOVEMENT in 10 MINUTES - Unity Tutorial
In this video I'm going to show you how to code full first person rigidbody movement. You can use this character controller as final movement for your game or build things like dashing, wallrunning or sliding on top of it.
If this tutorial has helped you in any way, I would really appreciate...
like the goggles go under the capsule and the backpack distances away from the capsule a bit
Sounds like a pivot point issue
I believe you just need to make separate gameobjects that will hold them in place
How would I have a game object move towards a target B from a starting position A, following a strict path, instead of moving exactly towards the target like done in Vector3.MoveTowards?
Would I have to implement A* or is there a different solution more adequate?
For more context, this is supposed to be for a tabletop game where the figures move between different nodes on the game board. The curved path is supposed to simulate the natural movement one does when moving figures around in real life.
I also thought of beziers, but then I'd have to define each node individually for each pathway, right?
i have a question is 8.5 a float or a double?
my instinct tells me its a float since surely it doesnt occupy that much space in memory
all i did was convert the float '8' to 8.5 and it generated this error
Instead of guessing, type it into your IDE and let it tell you what type it is
Did you read the error? It's quite clear
how is 8.5 a double tho
Floats use the f suffix
well I did but i assumed there must be something else thats wrong
if it's a defined path then beziers, or node traveling with interpolation
fyi you can do it with the animator
With the animator?
yep, can use that to travel on curves
Oh a manual animation for each path?
interpolate between nodes, yes
Sounds like a nightmare to manage in the long run I think
For example, if a path changes
like this???
Not very maintainable
if it's a defined path, then you need to do it manually somehow
Yes that's a float
It's not a question of how big or how much memory it takes. A number with a decimal point without the f is always a double
Wouldn't pathfinding automate this somehow?
well i still get an error in the same spot depsite there being no red
You didnt save
im acc so stupid
yep thank you
The same thing is also the case with long values btw.
If you want a long instead of an int, you must use l or L (preferably L because l is easily confused with 1)
Basically, you need to tell C# which value of the same literals you want (15 could be both an integer and a long integer, so there must be some kind of way to differentiate both)
Mm yup thanks
oh
Always wanted to try out Unity's pathfinding package so maybe I'll use this opportunity and give it a shot :D
I jus started unity im confused when i change the scale of an object it doesnt change a green out line apears this never happend before in my previous attempts in learning unity
i assumed that instead of saying a prefix for float/double, i specify if its a double or float at the begining like in standard C
It's the same way in C?
I haven't worked with C in ages but I'm like 80% sure it also uses the f suffixes
i've never had to use them so i dont believe they exist lol
Believe it or not but C# borrows alot from C
Like the compiler has a typing stage, where it must assess which type the literal has
It seems f is optional
The syntax is the exact same
C# has many of these pre and suffixes. For example, "@" will allow you to name a member after keywords
whereas c doesn't
As it should
Ah I see, C has an implicit cast from double to float, C# doesn't
That's the only difference^
Showing once again that C is very happy to let you do potentially dangerous things without complaint
I bet depending on your C compiler flags that may be an error under certain settings
"It's ur fault ur code crashed bro. It's a skill issue"
Pathfinding is for, well, finding a path... what you described sounded like you already have the path and just want objects to move on it which is not what pathfinding is for... so, which one is it? 🙂
C is considerably more weakly typed than C# / Java / etc
Definitely the latter!
The thing is I wanted to prevent having to redo anything if the path changes in later stages of production
replace java with c#
So, instead of having one target point, have a list that you adjust... and you can add some curve-thing that makes it smooth if you want
Mmm, I honestly have no idea how that would work and look smooth at the same time
null check
Lmao that was high above for sure :D
Well, if you want to find a path, you need a system that defines where you can move and all that, and on top of it find a path... and there's a single one by definition... so definitely no pathfinding 😄 pathfinding itself usually uses a graph and it finds a path on it to reach from A to B... it doesn't try to be smooth or anything, just finds a path
sorry... i looked and saw that first
In that case, ?. does a raw null check, which is why it isn't advised to use it for unity objects (no idea what that function returns so just random trivia)
I think it's because ?. is not overloaded by Unity
Yes you're right that's not the way to go
I'm not entirely sure what you have in mind (like what kind of game it is and what objects are gonna be moving, and are they gonna be moving all the time or just from one spot to another)... but all in all - you define a path by points, and if you want it smooth, you use some curves 🙂
It does a raw null check, you can't overload ?.
vs does throw me warnings on using ?. with monos
the animator thing sounds super weird, but am no expert
but null checking via comparison operator still works
Look it's the little known ?[] operator!
Yeah ? by itself is literally just an if statement (var foo = a ? b : c;)
though, checking if monos are null isn't that useful if destroyed on the same frame
nobody here has ever used ?[] I guarantee it
I see thanks
usually I'm always using them for events because why not
it's kinda the norm for events (if you mean doing ?.Invoke)
Rider actively admonishes you for leaving out ?. in events :D
yeah, I think vs does recommend it too
Wait so you can use ?. To check for static instance/singletons too??
You shouldn't use ?. with anything derived from UnityEngine.Object at all, which would be most singletons in Unity.
otherwise yes you are free to use it with any reference you want.
Haven't been doing it so far :]
I'm struggling to find a reason for having singletons that can be null though
Only for events and actions
I'm 10% considering adding some extension method that converts fake nulls to true nulls so that I can use ?. moar
Just came in mind and i blurted it out, don't booly me 🥲
public static T OrNull<T>(this T obj) where T : Object => obj ? obj : null;
ddol?
dont destroy on load between scenes
That abbreviation tho haha
That is the standard abbreviation
I think it's even in the docs
🤷♂️
Pulling from elsewhere where I posted about the difference with implicit/operator/?.. Kinda interesting
exactly, just not sure I'd actually use it or would I consider the code getting too ugly just so I can use ?. 😄
Where C# on that graph
put script where animator is
what i do though is make a seperate script just for a Unity Event
then listen to it from whatever script I want anim event from
How to ignore error messages like "UnassignedReferenceException: The variable damageDealer of Health has not been assigned."?
You don't, you fix them
There's realistically never going to be a situation where this function is triggered while damageDealer is not set, and even if it does happen nothing would break
You cant run the game without handling the NRE lol
Nope, this error only runs when the game runs
You can , doesn't mean you should
Then put a null check before you attempting to use it, if you think it's not a problem
Hahaha that's the thing... I can't find a documentation on how to apply the (?) null check to this line
LevelSystem damagerLevelScript = GetComponent<Health>().damageDealer.GetComponent<LevelSystem>();```
Wrap it in an if statement
!= null
? will not work on UnityEngine.Object
also seems weird to GetComponent to access a other component, so you can GetComponent again
def a design issue somewhere
what do i need to do so i can sprint?
first of all instead of crossposting and ignoring what I said, configure your IDE first. its part of the rules
but yeah all UnityEngine.Object stuff you need to use equality operators to check null cant use ?. and ??
I access another component that keeps track of which game object dealt the damage, then access that game object to get its LevelSystem.cs script
what dos it mean???????????????
!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
• Other/None
It means make sure your IDE is configured
what dose configuerd mean???
it does not look to be considering it is not highlighting types correctly
follow the guide the bot above posted
ideally You should be able to see the properly colored classes/methods etc..
it is configuerd and all of that
can i get help how i fix it?
doesnt seem it is.
it is
you were linked to the guides twice #💻┃code-beginner message
looking at your screenshot it is not
prove it
what do i need to do so it is then
to follow the guide for it
wear is it
Health.cs keeps track of GameObject damageDealer which is the GameObject that damaged this Health.cs component, XPOnDestroy.cs gives the damageDealer GameObject the XP
#💻┃code-beginner message
been linked to you 3 times now
If you have a better method, feel free to tell me. I'm doing this all from scratch with little guidance, so I probably went past a smart solution without realizing it
what will it look like when its done
types will properly be highlighted, autocomplete will work, it will be aware of all code in the project
it will mark syntax errors for you, and inform of missing symbols
what dose the atach mean in visiul studio
thats for the debugger
https://docs.unity3d.com/Manual/ManagedCodeDebugging.html
@crisp copper In the future, don't crosspost and stick to one channel.
Anyone know a fix for this?
stateMachine or player is null on that line
one of those is null, figure out which one
how should i fix it?
make it not null
!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
• Other/None
How? Sorry im new
i cant get in the vs Code
what does VScode have to do with anything
and the JetBrains Rider Dose not work
are you just clicking random shit?
The amount of times I've seen this exact answer.
jupp
idk what i shuld do
click Visual Studio. you have visual studio
its not that complex
VSCode is not Visual Studio
neither is Rider
ooo
Follow the instructions step by step, it has pictures
wear is the steps?
In the link..
wich
1 or te sekund visual studio?
Why does it feel like #💻┃code-beginner is for how to set up your coding envionment, while #archived-code-general is the actual beginner coding concepts channel
its because we're missing #Code-Pre-k
well by policy we do not help people who have not setup the tools properly yet. since why fight with errors that would be caught with proper tools
20% is null reference exceptions popping up from copied tutorial code.
Ill take NRE any day over unconfigured IDEs
@rich adder witsh of the 2 links frome the visual studio is the 1 i need to go in?
What's the rest?
Did you install Visual Studio with The Hub or Not ? the Links indicate that
doesn't hurt to just click the one that says manually and re-verify the steps
25% basic physics
20% basic shooting logic
5% is that one crazy guy who really should be in #archived-code-advanced that's asking about Compute Buffers.
some of advanced is people thinking stuff is advanced because its hard to them as well
The 5% compute buffer guy probably posts because because he doesn't think the concept is advanced and doesn't want to risk looking like an idiot
This is like some reverse Dunning-Kruger shit
compute buffers pretty general (the docs on the API could be improved though)
i have done al i can but it dose not make anything difrent
done what exactly? this is a blank statement
I have re installd evrything and made evryting
evrything that the studio link whanted me to do
when i would copy my code from visual studio into word, it would usually look like this
but now for some reason its like this, and i dont know how to change it back
its like me i dont know what i need to do but @rich adder cant help me
why would anyone ever do this
For a school project!
how much more can I help my guy.
Idk what you want me to say if I don't have eyes on your PC idk what u did and didn't do
Can someone help w my code
How do I fix a null?
post !code then
📃 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.
Have you shared it once? Stick to one channel
Alr
assign it a value
!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.
Did you do the first step yet? Did you identify which reference was null?
because it looks better than pasting pictures, and i can quickly change some things if i need to
Im still unsure on how to identify it
yeah sorry without context i thought you were literally storing code in a word doc. but yeah PraetorBlue gave you the info you need
Disagree, but why would you paste pictures either?
Debug.Log(somethingIwantToCheck)
need it for school coursework
Use Debug.Log or attach the debugger
inspect each thing that could potentially be null. See which one is
Can you not share the file itself?
has to all be on a single document
already showen how to do code blocks. prolly a case where they need to talk about some code for school and want snippets as examples
Everytime I try to attach the debugger it says failed to attach debugger
Then just use log statements for now
Is your IDE configured properly?
Yeah it is
I think they are submitting their work to their class
But yeah, I may be confused
Which IDE is it?
!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.
Can you stop please?
srry
How do I check which one it is?
@strong willow If you not posting a proper question stop spamming the channel.
um... read the title of the application you're running?
Oh that VSC
someone told me to do ! code
Hey everyone, I'm having a weird issue with the Raycast. Depending on the angle that the ray passes through the box collider the object is not detected. In the first screenshot it is hitting, but if I move it just a bit further it doesn't hit anymore. Is there any limitation for the Raycast that can cause it?
THe VSC debugger is not supported. I don't recommend using VSC
What should I use instead?
@strong willow If you continue spamming I will mute you
Rider if possible, otherwise Visual Studio
bro im not tryna spam istg
We were asking you to share your code, that is the guide for how to do so
There is no such limitation, it is likely an issue in your code or your scene setup
That command brings up a bot. You are supposed to READ the message and follow those instructions
Show the code you have using the process described by the bot
can i do it one more time to propperly read it
No
just scroll up
like ffs
is scrolling up diffcult ?
I just scrolled up, copied the link to the bot message, came back down and posted it for you to make it even easier 🤷♂️
I was trying to find the issue, I checked the layers and the colliders, everything seems in place. If I move the camera in order to be closer to the same spot that is not being detected, it starts to be detected. As if the raycast angle diffence to the colision point normal is affecting it. I'll try to check everything again. Thanks!
!warn 616261012714422312 Do not troll on the server. If you don't have anything constructive to say don't spam the channel.
fedleon has been warned.
istg im not trolling
Arguing with the mod is a real bad idea. Just share your code so we can help or leave
If the next thing you do is anything other than sharing code, I think you may be muted or banned
idk how even with the bot im confused whats a backquote
Use a paste site (listed at the top)
wow imagine that
a tool that actually gives answers!? amazing
Oof. Alright, I'm out
nvm imma jus help my self
`
yeah maybe you learn something by squeezing the brain a bit
stfu
no reason to antagonize
and yet im the troll
so i have grid of squares where the number is part of the GO name:
012
345
678
So it easy to tell that if i add one, it mean i can reference the next value as long value 0 or 1:
int goRight = index + 1;
However, how do I now what value to get of diagonal or up/down? It not easay to tell that the lower right diagonal is 4, eg
int goRightDown = index + ???
@strong willow Read #📖┃code-of-conduct . Read how to ask questions, in #854851968446365696 . And consider this as your last warning before ban about spam and insulting people who are trying to help.
I have a prefab that has rigidbody, collider & a few scripts attached, plus a health bar as a children
I'd like to use different prefabs for the "model" & collider within it while keeping everything else the same, what would be the better way to do this?
I've been at this for like an hour, there's always something new that breaks
please use 2d array
or row_idx * column_length + column_idx for flatten 1d array
man i was jus askin for help and i was the one getting insulted
telling you search something you're confused on isn't an insult lol
If you don't push yourself you will not learn
this?
plus im tryna learn
For the last time. If next thing you post is not related to your actual question you are out of here.
and ur not helping
would use 2d indexes then convert to the 1d as needed x + width * y is how you would convert a x, y coord to a 1d index
thank, i guess that is good starting point, but thing is my grid is created before runtime, so won't I have to apply reference to already created, or get position value? because it arranged like this:
nvm bro like i said imma help my self
a easy way to go up/down is +column_length or -column_length
thank, i guess that woudl work
Simply have an array containing the models and colliders, and swap these out when needed (either have them on and disabled or instantiate/destroy when necessary)
saying by helping yourself pushes the brain to learn is not an insult, thought it was a fair statement. Anyway I digress since Mod wants this convo done.. I shall not reply anymoee , Goodluck with your learning
Are you sure it's not just the raycast distance? Where is the ray originating? What max distance is being used? How are you drawing the blue line?
the models need to be within the root (parent) object part of the prefab though
how can i 'swap them out' ?
@rich adder am i done now???? or do i need to do enything else?
👏
now you're coding Properly
I have a confirmation "popup window" ui element with a confirm and cancel button. I'd like clicks outside of the window to close the window/be equivalent to pressing the cancel button, and I'd like for other UI elements to not be selectable while the popup window is open. How might I do this without having a giant invisible button over my entire canvas?
Simply have them anchored to the parent object (or make an array of prefabs and instantiate them as a child of the root object)
so can you help me now hov i make so i can sprint on shift?
Basically separate the visuals and colliders from the root and have them as a child
btw you cant just +1 to go right since you may go to next row
imagine index 2 + 1 = 3
you have to check
separating them is fine, a hierarchy along the lines of this should work:
-- Colliders
---- Collider1
---- Collider2
-- Visual
---- Model1```
ok post the script (not screenshots anymore)
!code (read below )
📃 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.
yea, I see now
@rich adder what will this help me whit?
oh you mean the bot msg
yea
need to see the script
I guess there is also big benefit to assign row and colum nto each unit because then u can check if a rxc exists, eg if youre at 1x3 and diagonal (right and down) is 2x4 but that is out of bounds and my code should catch that
already mentioned earlier how to sprint though
in the bot messeg it ses add a cs to the first line,
so i should add cs in evry scripts or what?
nah you are posting an entire class that is def a Large Code situation
you send it via link
also
wear?
I guess one other way is to create the grid with the gird layout group etc. and other components that deal with the formatting automatically, then insert each unit at runtime and assign row and column programmatically (instead of get reference of each preexisting one which is more work)
@rich adder Don't think you ever judged this, still bad design?
Dont just copy and paste it though, try to understand why its that way
I dont know the full context and what those scripts even do though, also seems you mentioned a different script than what your GetComponet was
I do the first part in my games (tracking who passed damage). I think the XPOnDestroy may be fine, it does introduce a kinda three way coupling, but if the health script is the intermediary (the one passing the message back to the damage dealer) it would be fine
How do I identify a Null and How do I fix It?
We told you multiple times how..
feel instead ofa XPOnDestroy would just have health invoke a event when it reaches 0, what subs can decide how to handle that
I still dont know mb
Wouldn't that make health.cs unusable though?
You need Debug.Log eachh one of those things and see which one prints Null
For anything that isn't an XP giver
it can only be those few things on line 55
Why?
yeah i linked them there
they didn't get it either lol
Debug.Log(myObject1)
Debug.Log(myObject2)
or combine them
Some objects might reach zero HP without invoking an event
Yeah, that is fine
TryGetComponent, if not XP then don't try to give xp
oh wow, it was that simple, tyvm
The event could just let the damage giver know the thing died, or just NOT do the event. It can be quite dynamic