#💻┃code-beginner
1 messages · Page 6 of 1
So, I have the card, and when the button that is attached to the card is pressed, it moves forward 1 space on the Vector2Int array.
I made the array from a chess making tutorial but our ways diverged and it's getting hard.
whats the issue you're having?
hatebin good lord
!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.
These are my scripts. In gameboard, look all the way down to moveforward and moveforwardpart2
It's declaring a null reference.
I made a script that selects a game object you pressed and wanted to make the selected card move forward 1 space in a grid.
But I think I'm really struggling on transforming the raycast hit.transform to a grid []
I can't even see the scripts so 🤷
Line number?
270
:/
So its either RubyRose or unit that are null. Go ahead and debug log or debugger check them
Sorry, but i'm kinda bad.
What do you need to write in order to debug it?
Transform RubyRose = highlight.Find("RubyRose");
Debug.Log($"Ruby Rose: {RubyRose}, Unit: {unit}");
Try that right before your error line
avoid Find Methods :\
Not wrong, but its not necessarily the problem
could be
is highlight a transform ?
I think their both null
Okay yeah they are both null
Lets look at rubyrose first
Are you sure highlight is not null?
is highlight a transform ?
You can check this with your inspector on debug mode and play the game
huge difference between GameObject.Find vs Transform.FInd
private Transform highlight would say so.
That is assuming highlight isnt null in itself, your assignment of highlight is in an if statement so it might never get assigned
true
but if it isn't then its looking in the wrong spot too (possibly)
we need to also see the hierarchy
wait what the hell
lets see the hierarchy
whatd you change the debuglog to?
your hierarchy architecture is confusing
anyway okay if its not null then yeah, hierarchy
Screenie your hierarchy
With all children shown
'exposed' is not the word in that sentence
which one is highlight
Okay so your highlight object is the gameobject named RubyRose
highlight is Ruby Rose
so your code is looking for a child under RubyRose named RubyRose
is that what you intended?
yikes
yeah this is a pretty goofy hierarchy architecture
if its on the same object just [SerializeField] it
oh no
then I messed up
if you must use runtime search (for spawned runtime objects) then use Tags.
or components
I actually wanted to move the highlighted object 1 tile forward on the array.
I originally did do highlight.position but it also kept calling null, specifically on the part where it says = unit.transform.position
hmm unit prob was null
fix your Find methods issues
you have a lot of Finds lol
finds as in, Genunit unit and int x etc?
Inside the () of the method?
Oh, you mean up there?
all the menu stuff
transform.rotation = Quaternion.Lerp(transform.rotation, ReferenceHolder.Instance.characterReference.FOW_Revealer_Rotation, Time.deltaTime * multi);What does this error mean?
ohhh, yeah. It's kinda necessary tho. I do need to open the menu up upon being highlighted
Do you know a way to make it perform better?
yes lol
did you read the link I've sent though ?
it talks about this
and alternative better ways
oh nice tileset
mixture of 4 
your rotation imploded xD
(i genuinely don't know sorry)
Based on the unity forums
one of your quaternions is (0, 0, 0, 0)
otherwise known as undefined
oh
yea that can be the problem since the revelaer roataion is using a blank quaternion
Also you're using lerp wrong
not really
this is how you do smooth movement with lerps
You shouldn't, but people do it
That's not a valid reason to do it
i want my rotation to move fast when player look at opposite direction
im fine with a lazy lerp for this one
wouldnt quaterion.slerp be better ?
probably change into that one
If you don't need exact outcomes or durations and aren't too worried about differences across frame rates, applying lerp like this is a common creative way to smooth movement.
It's still an approach you can use, it will yield an okay result depending on what you consider okay
nvm, lerp is better
wont slep be more unpredictable?
how to know which direction it will decide to turn?
slerp gives you an ease in ease out, while lerp is linear this looks infinitely more complicated than what i know
direction seems irrelevant
How do you know which direction lerp will turn?
Broken lerp is usually associated with an inconsistent source
And constant/random point in interpolation:cs Lerp(source, target, point)
🤓 "Your using Lerp wrong."
in a nutshell for rotation slerp is more consistent smooth rotation,
lerp on rotation makes it slow down and speed up
That really got me
ya the spelling funny
hey, do any of you know how it would be possible for an object to have cracks that mean it is going to be destroyed? (eg: if you saw Minecraft, the iron golem also presents those cracks that signify its life point and each time it is lower, the more cracked it appears)
That's just changing a texture
I don't know how to call the game object child itself despite watching many tutorials. GetComponent always gets the component of an object but never the object itself through name, right?
So how am I supposed to change my "find" functions with getcomponent
Likely not a coding question, try asking #💻┃unity-talk
If it's a child of this object, why use Find or get component? Just make the field public or serialized and drag in the reference
Transform Find?
https://docs.unity3d.com/ScriptReference/Transform.Find.html
Preferably what digi said though
upss sorry
The script itself was on the general game handling object. If I drag in the reference I would have to drag in the children for every card I'm making
I've also seen this way of getting children but it gets every single children, surely this can't be the answer
So is the object you're looking for not actually a child of this object before the game starts?
it's actually not
which is why I used find
What makes it become a child of this object then?
How do I make two scripts send information to each other? I want to send information to another script from my method
Reference the other script, then you can call functions on it or access values from it
https://unity.huh.how/programming/references
I need to access the child of an object that is being highlighted after I click on it with a mouse.
The script for the ray that highlights the object is not inside the object itself
can I change a setting of a material to only one of the gamobjects that is using it thru script?
This function is extremely wasteful
What is the method by which the object you are looking for becomes a child of this object
is it instantiated there, is its parent set, or what
Put a script on the root of the highlighted object (or whatever the raycast hits) and just call a function on that script. Let that script sort out the reference details
Yes, change a property on the .material. If you do want it to affect all of them, you would use .sharedMaterial
THANK YOU THISIS WHAT I NEEDED
ok I will change to something simpler, is there any method or way to detect if my object has an impulse type force in its rigid body but with a certain speed? I only find addForce
...what?
Are you asking how to check if the velocity is over a certain amount?
You can get the magnitude of the velocity and check that
What do you mean "with a certain type of mode"
The ForceMode determines how the force is added to the velocity
there's not different "types" of velocity
😦
wait
that was because I was trying to imitate the GMOD's explosive barrels, they act like this: if the player collides with them while they are against a wall they do not explode (unlike my case where they do) and also if they fall from a great distance,the only thing that makes them explode is a type of force that is when you use the gravity gun or let another barrel explode next to it
I will send comparison video
like if you drop exploding barrel it doesnt explode but if you use gravity gun to launch , it will impact something and explode ?
they probably just check a certain threshold for velocity on impact
Or just set a flag like can_explode when you fire it
mmm you two gave me an idea
For an example..
Script A is attached to GameObject 1
Script B is attached to GameObject 2
Within ScriptA I make a public GameObject pointing to GameObject 2
Within ScriptB I make a public GameObject pointing to GameObject 1
Is this the proper way to set this up?
This way they can share variables and update each others variables correct?
No good reason to use GameObject as the variable type. Just use ScriptA and ScriptB directly
use the script type instead of GameObject
Using GameObject just adds complication to your code and makes it more prone to accidental errors when assigning them in the inspector
ScriptA should have a public ScriptB pointing to ScriptB
ScriptB should have a public ScriptA pointing to ScriptA
Why bother dealing with the GameObjects when you actually want the scripts
Also "sharing variables" and "updating each other's variables" are not generally considered good practice. It's better to only expose the bare minimum required and to do so through the use of Properties and Methods, rather than directly modifying the variables on another object.
That is a better way to put what I wanna do
public Scriptable path
or what is the way to reference a script
Like that, assuming your script is called Scriptable
Or scriptableobject
public WhateverTheClassNameIs myVariable;
Oh ok. I can directly reference the script name
Public FootballController name
https://docs.unity3d.com/ScriptReference/SerializeField.html sum good readin'
Thanks everyone. Back to work. I appreciate it
im having the problem that when I reference a script im getting the error object reference not set to an instance of an object. I also have set the component too
where are you getting the error
neither circled line can possible throw that error
the error will have a filename and line number
btw this code will only work if the two scripts are attached to the same GameObject. Which is not what your example said earlier
you earlier said they're attached to different objects
ohh ok
this looks like SlimeStats.cs line 27
Alright is there a way to get from a different script?
assign in the inspector, or assign at runtime
in this example it seems like it's an enemy you're spawning
yeah im trying to access another code from a different script
kinda but like im trying to make the slime only move when it gets into the slime trigger range
why not just grab it when you get an OnTriggerEnter then
Having some issues with my shotgun. I have it setup to create bullet holes when a raycast I fire off hits a target. However, when I mash the fire button, the bullet holes get created before the animation goes off.
{
isFiring = true;
ammoClipLeft -= 2;
Debug.Log(isFiring);
cameraBobbingScript.enabled = false;
lastPos = cameraPos.localPosition;
cameraPos.localPosition = startingPos;
//source.PlayOneShot(shotSound);
GunFiringAnimation.SetBool("aniTrigger", true);
DynamicCrosshair.spread += DynamicCrosshair.shotgunSpread;
for (int i = 0; i <= numOfPellets; i++)
{
Vector3 direction;
Vector2 randomSpread = Random.insideUnitCircle * spread;
direction.x = randomSpread.x;
direction.y = randomSpread.y;
direction.z = 0;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition + direction);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, shotgunRange))
{
Debug.Log("Shot has collided with " + hit.collider.gameObject.name);
hit.collider.gameObject.SendMessage("GunHit", shotgunDamage, SendMessageOptions.DontRequireReceiver);
Instantiate(bulletHole, hit.point, Quaternion.FromToRotation(Vector3.up, hit.normal));
}
}```
cute graphics
check your bool that it's not being switched too early
sounds like you're not really making sure that the animation is done before allowing the code to run again
I do have animation events setup, so Im thinking maybe it might be set to that?
where does isFiring get set back to false?
when the animation is finished (or triggered by an animation event near the end of it I have setup)
right - show how you have that set up
sure
I dont wanna move the event any earlier because then it makes the animation look jank
{
GunFiringAnimation.SetBool("aniTrigger", false);
isFiring = false;
Debug.Log(isFiring);
cameraPos.localPosition = lastPos;
cameraBobbingScript.enabled = true;
}```
so ive been following this guide but i seem to have a error on the last }
no credit for me lol, I only did the gun assets 
enemy sprite is just a basic one Im using for debuggin/setup
but yeah Im not sure what to do here, on the one hand, I dont wanna set it up so the animation ends too early. On the other hand, I want it setup so the bullet holes dont get instantiated too early
ohh I meant the gun mainly
Thanks!

really happy with how it turned out! Using this project as a proof of concept for myself for something Ill work on after Im done with my last project
OnMove is inside FixedUpdate in your version of the code. Watch how in the video FixedUpdate ends on line 36
And yours, on line 47
yup, you made a nested method
what are those other animation events?
Are you sure none of them are accidentally doing it early?
nah those are setup to just play sfx at the right times lol
that or control gun variables like ammo and recoil
nothin that would create the bullet holes
just a bunch of really simple methods for the animator to call to make the gun sound/play good
Perhaps execute the firing function at a specific frame for your gun animation?
Because it's doing it on the first frame of the gun it seems, no?
double check that they're pointing at the correct functions
That did the trick!
Thanks again! 
ye
Hi, I'm using a rigidbody for my first person controller. I want to have it interpolate as it helps smooth when moving and looking (objects are jittering when interpolate is off) but when interpolate is on I can get this weird "feedback" effect that never stops. Any ideas why or how to fix it?
so they've matched up line for line but that last 41 is still red and errors
They're not, because you're missing the one } that will close your class declaration
Class declaration opened by a { right after class PlayerController : MonoBehaviour on line <unknown, cropped out>
what would be the purpose of having a public void over a private void?
Public means accessible from outside the class
So you would be able to call the method (not called a "void") from another script
O ok, so if I want to use a method in another script I need a public method
(void is the return type, meaning the method does not give a value back to you)
Correct
even if the script is referenced like
public PlayerController playerController; // PlayerController Script
I have that in my other script to point to the player controller script
Yes, the access modifiers you put on the variable here, are separate from the one you put on the method
In some case you'd still want parts of your script to be accessible from the outside, others kept private
so is it bad practice to always just use public methods?
and they were public that wouldn't work out
thre's all kinds of reasons you would want private methods
It's kinda something you learn upon. If you're not too sure, keep it public honestly.
there's lots of things you will want to be able to do internally in a class that you don't want to expose to the rest of the program
When you don't want them to be accessible from the outside is one
There's a reason private is the default access modifier
Like, you don't want anything that has access to the player script to be able to call Die() on it
Then you've got languages like python where it's not really enforce, so you're usually having to modifiy variable names, which is why you may see underscores before them in some context.
public class FootballController : MonoBehaviour
{
public GameObject football; //The football
public GameObject following; //Follow the player with the football
public PlayerController playerController; // PlayerController Script
void Update()
{
Pass();
}
public void Pass()
{
}
}
So I pointed to the player controller script. How do I call a method from that script within a method in this one?
why am i getting this error for a public void in a public class?
playerController.MyMethod(), similar to how you'd access a variable on it
enum Class is private. void GetState is public, which would expose enum Class outside of JobBaseStatsData. This breaks the restriction private provides, so the compiler prevents you from doing it
ahh i see ty
If the enum is meant to be used outside the class it was declared in, consider taking the enum out to its own file.
It's a type after all, like classes or structs
yeah that's a good idea
Lol got my first stack overflow error ever.
managed to get the code to complie now with no errors. but doesnt seem to move the character
Thanks for the assistance got the scripts working together now.
Be glad Unity catches those, in regular C# app, a stack overflow terminates the process (hard-crashes the app)
Is there a quick code cleanup button to fix my formatting
within visual studio that you know of
Thank you
when i try too make a custom cursor in build settings i get Failed to set the cursor because the specified texture ('Rat Cursor') was not CPU accessible.
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
and idk how too fix that
Hi everyone! Can someone help me with an issue I'm having with my game? My game is displaying a text GameObject that tells the player when a powerup is available. This text disappears when no powerups are available. However, when my plaer completes the game by achieving a target score, this text GameObject should also disappear. I have used this part of code for that:
//Powerup availability
if (GameObject.FindGameObjectWithTag("Powerup Pickup") == true && (player == true))
{
powerupPickup.SetActive(true);
}
else
{
powerupPickup.SetActive(false);
}
But for some reason, the text continues to show when my GameComplete script runs. When my GameCompelte script runs, the player is set to false.
Here is the full script, and a video showing my issue: https://gdl.space/ewivujizib.cpp
Thank you for helping!
Maybe instead of checking if the variable is null or not, you should check if it's active? player == true
== true is never needed btw, it's extraneous. But yeah you're checking if those objects exist basically rather than checking if they're active.
Also if you already have a direct reference to the object: powerupPickup what's the point of using GameObject.FindGameObjectWithTag("Powerup Pickup")??
Thank you, that's helpful. I will try to learn how to check for if something is active.
Hm, I didn't think of that. Are you saying I could add a public GameObject in my script, and assing the prefab inside my GameManager object in Unity?
Now that I think of it, that wouldn't work, as there are (Clone) objects of the prefab.
Cache the cloned instances, if needed.
I'm saying it sounds to me like you already have the reference assigned and can just use it directly
Maybe you can back up and explain when this code is meant to be doing
float x = Input.GetAxis("Horizontal");
camHolder.rotation = Quaternion.Euler(camHolder.rotation.x, camHolder.rotation.y, x * rotateForce * Time.deltaTime);
if (x == 0) { camHolder.rotation = Quaternion.Euler(camHolder.rotation.x, camHolder.rotation.y, 0f); }
is there anything wrong with t his
Yes. rotation is a Quaternion, its xyz doesnt mean the same as euler angles
{
ringMesh = new Mesh();
GetComponent<MeshFilter>().mesh = ringMesh;
CreateRing();
}```
I am creating a mesh through code, there is no mesh in the project file that its looking at or pointing at, however every instance of this component writes to the 'same mesh' as in they arent instanced per component, changes to one changes the other 🤔 How do I correctly make the meshes independent?
You should replace rotation.x/y with eulerAngles.x/y
wait
amma try that
What is it supposed to do tho? Plugging an input into the Z angle looks a bit off.
its the not rotating in the y axis
You never said what the code is supposed to do
to rotate the cam to the direction the player moves
actuaklly it looks like OnEnable is just never being called
I don't know why though
why are none of these ever being called in editor?
ive been debugging this for four hours so my brain is just shot
Pretty sure you need the ExecuteInEditMode attribute
If you want it to work outside of play mode, that is
Remember to Destroy any leftover Mesh objects so they dont stay lingering in the memory. Also Mesh.Clear() on an existing mesh is way faster than creating a new one
(In edit mode you should use DestroyImmediate)
private void OnTriggerEnter2D(Collider2D collider)
{
if (collider.CompareTag("Football"))
{
thisAnim.SetBool("hasBallAnim", true);
Debug.Log("Picked up football");
football.SetActive (false);
footballFollowing.SetActive(true);
}
}
How do I add a delay between football and footballFollowing
yield return new WaitForSeconds(duration); gives an error.. is there another way to go about this
you would need to use a coroutine if you want a delay
so put this code within a coroutine and put that in the update?
you can just put the line you want delayed into a coroutine right after a yield and just start the coroutine right there in OnTriggerEnter2D where that line is currently at
{
if (collider.CompareTag("Football"))
{
thisAnim.SetBool("hasBallAnim", true);
Debug.Log("Picked up football");
football.SetActive (false);
coroutine here
}
}
The coroutine
yield return new WaitForSeconds(5);
footballFollowing.SetActive(true);
like that?
not coroutine here but StartCoroutine here, but otherwise, yes
IEnumerator PickedUpFootball()
{
yield return new WaitForSeconds(2);
footballFollowing.SetActive(true);
Debug.Log("Picked up football");
}
private void OnTriggerEnter2D(Collider2D collider)
{
if (collider.CompareTag("Football"))
{
thisAnim.SetBool("hasBallAnim", true);
football.SetActive (false);
PickedUpFootball();
}
}
Worked just gotta fixed up my logic.
Use StartCoroutine instead of calling the coroutine like a method
no,
StartCoroutine(PickedUpFootball());
Otherwise it will either stop at the yield, or skip the yield, I forget which
Ok. I trust you. Just like to know the reason behind doing what I'm doing
Ok, got you
The reason is very simple, because that's the way it works
haha fair enough
hello i need help with unity switch weapon
how can i try to find information1, 2, and 3 using i to find the public value in this gameobject?
Cardchosen is the card on the first screenshot
rate my class https://pastebin.com/qTGzY24W
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.
If you ever find yourself numbering variables, it means it's time to use a list
Also there's like, fourteen other things wrong with this snippet
i mean, that's also why i'm in this channel...
could anyone give me some pointers on how to code a drawing system in unity please?
drawing_system *ptr;
Jokes aside, probably with a texture modifiable from the code at runtime
Issues I see:
You declared i2, but are using i..
You put a semicolon at the end of the if condition.
You should absolutely just be using a list, or an array, then use the i as an index
can anyone fix this???
mate that is 60 dollars
my company wanted to make clone of power wash simulator and without this asset it would be liability 😛
fix what?
watch it
i am aware of all of these mistakes, i just didnt correct them cos to be fair i wanted to do it affter finding a way to do it, but how would i use a array for that?
because what im simply trying to do is trying to type information1 using i2, kinda like you would normally do with 2 strings using a +, idk how i would do it here tough
I don't know what type information is, but when you create the prefab, add the information in the array, then in that for loop (when you fix the issues), do this:
information[i]
so i would have to manually make a array THEN make the for loop (using the array with the info)?
You are manually entering the variables here:
#💻┃code-beginner message
It's exactly the same, but into an array or list instead of separate fields
Simply put, don't do it with string concatenation... that is a terrible way to do it
Sure
can anyone help?
I did not see that
the vid?
You gave a video and no other information
show script
private void FixedUpdate()
{
//Rotate camera in the direction the player moves in
Vector3 rot = camHolder.eulerAngles;
float x = Input.GetAxis("Horizontal");
rot.z = Mathf.SmoothDamp(rot.z, x * rotateForce, ref velocity, smooth);
if (x == 0)
{
camHolder.rotation = Quaternion.Euler(camHolder.rotation.x, camHolder.rotation.y, 0f);
}
camHolder.transform.rotation = Quaternion.Euler(rot);
}
btw not likely this would ever be true
if (x == 0)
??
you don't want to compare floats with ==
find a better camera rotation script 🤷
idk rotations too well
idk if i have to thanks u or not
also why rot.z
cuz why not
Hey everyone, i'm trying to change the offset in a cinemachine camera through script, i can't seem to access it though?
I'm stuck on this so not sure what to do
Ooooh i might have it actually
ur a legend
Back again, got another question. So Im working on a simple recoil system for my gun in Unity, but want it to be different. My current implementation has it return to the postion from when the gun was fired (like most recoil tutorials I've checked have it do), but Im more looking to add in a system that knocks the camera rotation up and around with a procedural generated num instead.
I feel like its easy but Im having a hard time wrapping my head around it
private Vector3 targetRot;
[SerializeField]
private float recoilX;
[SerializeField]
private float recoilY;
[SerializeField]
private float recoilZ;
[SerializeField]
private float snappiness;
[SerializeField]
private float returnSpeed;
void Start()
{
}
void Update()
{
targetRot = Vector3.Lerp(targetRot, Vector3.zero, returnSpeed * Time.deltaTime);
currentRot = Vector3.Slerp(currentRot, targetRot, snappiness * Time.fixedDeltaTime);
transform.localRotation = Quaternion.Euler(currentRot);
}
public void RecoilFire()
{
targetRot += new Vector3(recoilX, Random.Range(-recoilY, recoilY), Random.Range(-recoilZ,recoilZ));
}```
Ive tried checkin every tutorial I can find, but to no avail unfortuneately
(how it currently looks)
void Update()
{
if (football.SetActive(false))
{
{
FootballFollow();
}
}
}
what is the proper way to do what i'm trying to do here
Hey. I'm stumped. No issues in my code or anything. I'm trying to make a pickup system and I need to be able to add '1' to an int. Unfortunately, [Int name here] + [number here] doesn't work. does anyone know how to fix this? here's the code: ```cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class PartPickup : MonoBehaviour
{
public int partsCollected = 0;
public int partsNeeded = 3;
public TextMeshProUGUI progressText;
// Start is called before the first frame update
void Start()
{
this.gameObject.SetActive(true);
partsCollected = 0;
partsNeeded = 3;
progressText.GetComponent<TextMeshProUGUI>();
}
// Update is called once per frame
void Update()
{
transform.Rotate(5, 5, 5);
}
public void OnTriggerEnter(Collider other)
{
partsCollected + 1;
progressText.text = partsCollected + " out of 3 parts collected";
Debug.Log("player collision has been detected.");
this.gameObject.SetActive(false);
}
public void ChangeTextToNextObjective()
{
if (partsCollected == partsNeeded)
{
progressText.text = "Return to Traf's cone.";
}
}
}
if (!footbal.isActiveSelf) @valid finch
thanks
!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.
You still need to save the result in a variable or do partsCollected++
you should configure ur IDE first
I have no idea how your VS isn't warning you about this
there is a big syntax error
thank you so much
sorry
alr well you don't because it would be underlining the clear syntax error
It's because it is a syntax error that should have a big warning
So something with your IDE is wrong
it doesn't show that in discord. it's clearly highlighted in VS. I'm sorry I didn't make that clear from before.
alr
fixed now. thanks
Perfect. TYSM
isActiveSelf gives an error
It's just activeSelf
https://docs.unity3d.com/ScriptReference/GameObject-activeSelf.html
Thank you both
I think unity is trolling me hard. Why I cannot add this script as a component to my object? No errors in the console
you have duplicate class/script names
whicj will give an error in the console
Refresh assets
My dude it's literally in your screenshot
this happens to me sometimes on2022
?
read this @polar acorn
I already have the script
I cannot add it
https://hatebin.com/lwefatiwcd is this correct way to stop coroutine if its running looks like it doesnt restart if I run another just before first one finishes but ive got a bunch more stuff so idk
common bug on 2022 afaik
@rare basin notice how it says duplicate class, so you got the class in a script not called the same
i restarted unity didin't help i can try to delete Library folder
right click in project folder and do Reimport
not reimport all
alr let me try
Ah, I just saw the error message and the last image, discord cropping cut out the rest and I didn't see there was already code
im having so much issues with 2022
everything
Oops. One more issue. I have 3 seperate GameObjects being picked up. Each separate from eachother in the hierarchy. Do I need to add them onto a parent with a manager script? They all have their own version of the script with the same values set. It feels hard to explain.
which is a buggy mess compared to 2020
which is a buggy mess compared to 2019
need I go on?
lol unity 5 ftw
gonna send pictures in a sec
2017, best yet
just trying to find out what the heck I'm supposed to take a picture of
what are you trying to do ?
like with code
Yeah, I was going to ask that. What the problem you're having?
I'm trying to change a text UI depending on the current value of an int. Unfortunately due to the fact that there are 3 seperate gameobjects with the same script, every time I pick one up, it just deletes the value and replaces it with 1
which was the same value to begin with
you only need 1 script to keep actual score and deal with text
have the smaller pickup script only let that main script add +1 to a count
ok. So, I make a new script, make it so that it disappears upon collision and change the value of the main script?
so, I do need a parent manager!
just make a class for example StatsTracker or whatever you're keeping track of
when you pick up, the script on pickup should ideally have reference to that statstracker, or you can make it a singleton, have a static instance of it to easy access
ok... I am highly unfamilliar with singletons
I'll try my best and I'll check back in a sec
they're pretty easy
and powerful
just dont use it on everything ofc
alr. thanks
Evening, I'm having a problem with animation events, I have this function in my player animation script:
public void PlayHit()
{
print("yay");
GameManager.instance.GetAudioManager().PlayHit();
}
but it is not in the dropdown menu, instead there are a bunch of functions I don't care about.
is the script on the same object as animator
if (Input.GetKeyDown(KeyCode.Space) && thisAnim.("hasBallAnim", true))
Trying to do an action if this animation is true and the player is hitting space
but no othere time
Wdym animation is true
you want a specific clip ?
Parameter on your animator?
public void Act()
{
if (Input.GetKeyDown(KeyCode.Space) && thisAnim.GetBool("hasBallAnim", true))
{
footballController.Pass();
thisAnim.SetBool("hasBallAnim", false);
}
}
this wont get you specific animation, just if parameter is true
Not understanding
if you want to check the Animator parameter, use the link.
if you want to check for specific animation/state
Animator.GetCurrentAnimatorStateInfo(0).IsName("AnimationName")
damn..
If GetTile() always return a TileBase, how may I check if the returned tile is of a different type?
For example, I have two custom tile classes: LandTile and WaterTile. How may I check if the tile return is water?
Won't using returnedTile is WaterTile always return false, as returnedTile will be TileBase?
GetTile<MyType>()
Yeah, but what if I use GetTile<WaterTile> but there is a LandTile at the position?
you get error prob
you do checks
if (Input.GetKeyDown(KeyCode.Space) && thisAnim.GetBool("hasBallAnim", true))
can you write that with proper syntax.. I am not getting it..
bruh
been looking at the coding hints
That's exactly what I'm asking, how to check
But nvm I think I figured it out
Through the magic of polymorphism, is can still do the check
Think I got it
if (Input.GetKeyDown(KeyCode.Space) && !thisAnim.GetBool("hasBallAnim"))
if pressed spacebar and hasBallAnim is false
Yeah logic was wrong. Now I gotta step through the code to see where the logic is going wrong. I got rid of the ! there are other logical issues though.
thank you again
what do you expect happening and what is happening instead?
Oh.. something is just not right. I have to double tap the space bar to get it to happen. So apparently something is set to true or false when it shouldn't be. I'll find it. Could also be the WaitForSeconds. I'd share my code with you if you want to see. I don't need you to fix any of it.. just curious on your thoughts as to how poorly set up it is.
public override void RefreshTile(Vector3Int position, ITilemap tilemap)
{
for (int x = -1; x <= 1; x++)
{
for (int y = -1; y <= 1; y++)
{
Vector3Int neighbourPos = new Vector3Int(position.x + x, position.y + y, 0);
RefreshTile(neighbourPos, tilemap);
}
}
}
Why is my refresh override causing an infinite loop? Been waiting for Unity to enter play mode for like 6 minutes now lol
Well it should just be a StackOverflowException, but you do have infinite recursion here
Oh damn
you're calling RefreshTile inside itself unconditionally
but it shouldn't freeze Unity
that's frozen
yeah that's frozen
on the first frame of the game
This is clearly bad but I suspect you probably also have another infinite loop elsewhere
Well, every time you call RefreshTile, it's going to call RefreshTile nine times so that'd do it
Anyways, I adapted from the scriptable tile example tho, I just didn't use a HasRoadTile check cuz I wanted all neighbours to refresh
but you're checking all neighbors of all neighbors... ad infinitum
not to mention that when you check your neighbor, it will then check you, and vice versa
also forever
Any ideas to limit it?
recursion always needs a base case
You need two things:
- keep track of which tiles you checked already and skipped them
- make some kind of "maximum depth"
Why isn't the one on the example not causing an infinite recursion? https://docs.unity3d.com/Manual/Tilemap-ScriptableTiles-Example.html
Because it only calls itself sometimes
It's not recursing at all
it's calling tilemap.RefreshTile
Actually, yeah that's a different refresh tile
I didn't realized I was not calling the tilemap
although I guess that might be ultimately calling this function
the other thing is that they are checking a condition: if (HasRoadTile(tilemap, position))
Yeah, but that is only to refresh the same tiles
I'll test with the tilemap refresh, see if it causes the same behaviour
Nope, with tilemap refresh
all is fine
why when i pickup the items in a small window, then enlarge and drop they are like twice the size?
Could swear I read the example as using recursion. Sorry for wasting your time.
but then when i pick them up and drop in the same size game window
it works properly
I can only assume it has to do with your code
yeah let me show u the drop code
public void Drop(Item item)
{
audioSource.PlayOneShot(item.itemData.dropClip);
item.transform.position = dropPosition.position;
item.GetComponent<Rigidbody>().AddForce(dropPosition.forward * 5f, ForceMode.Impulse);
item.GetComponent<Rigidbody>().AddForce(dropPosition.up * 2f, ForceMode.Impulse);
item.StartCoroutine(item.StartCooldown());
}```
im just setting the position
where does item come from
where do the objects go when you pick them up
show the code that calls this code
and/or the full script
Yo what is that IDE, looks sick
Item is this
using System.Collections;
using UnityEngine;
public class Item : MonoBehaviour, IInteract
{
[Header("Item")]
public ItemData itemData;
public int amount = 1;
[HideInInspector] public bool isReady = true;
public string interactText { get; set; }
private void Awake()
{
itemData.isDiscovered = false;
}
private void Update()
{
HandleText();
}
public void HandleText()
{
interactText = $"[F] Pick up x{amount} {itemData.name}";
}
public void Interact()
{
InventoryManager.Instance.Pickup(this);
}
public IEnumerator StartCooldown()
{
isReady = false;
yield return new WaitForSeconds(1f);
isReady = true;
}
}```
Rider I think?
item sits on the actual game object
idk visual studio code
do you have scale in itemData?
this doesn't ake sense to me. You're just setting its velocity to 0? How is it disappearing?
ah that's why
the slots are canvas images
yeaaaah
those will scale differently obviously on different resolution
You will need to save the old scale when you pick it up
and restore it when you drop it
e.g. in Item you can do:
Vector3 originalScale;
void Awake() {
originalScale = transform.localScale;
}
public void OnDrop() {
transform.localScale = originalScale;
}```
just call OnDrop on it when you drop it
i mean that makes it kinda easy for you right? It is pretty weird though
yeah
i'll do that
i was parenting it to just keep my hierarchy clean
it doesnt really matter too much
Which function exactly do you want to take a string parameter?
and where is the string going to come from?
and is ButtonTable[0] the GameObject you want to pass in?
hi there - thinking about a second map for our game, is the pro best practice to just duplicate the entire game config as another scene and setup the new scene? seems difficult, i want all the same managers/players/inputs etc just on a different map
use prefabs
is there a cleverer way to load a new scene/map/bit of scene that allows me to change the 'level' without rebuilding all the gameobjects/script mappnig etc
yea we have prefabs for some things, defo could do more, you mean setup prefabs with all the right scripts etc?
Well I wouldn't set up a prefab with the wrong scripts
additive scene loading - I think i've read that somewhere
@wintry quarry all my scripts are the wrong ones 🙂
is that where unity partially loads another scene into the current one?
i'll google it
yes
ace - thanks for the pointer
for example if you have a bunch of baseline objects you need in every scene you can load that bootstrap scene first then additively load the actual game levels
yea makes sense, I think i saw it used for big sprawling partial load maps but makes sense for smaller setups, load the new parital and boot the player and camera over there
also one more thing, when i just drop an item, and pick it up the text disepears, but when i split the item, and i pick it up, the raycast in my interaction script isnt detecting that it got picked up
this is my split script
i have no idea what is happening
!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.
the text is supposed to remain if you arent hovering over the item for 1.5 seconds, thats not the problem, its the picking up
maybe something with instantiating the item when im splitting?
find a better way to do it
this is the better way
Can I show you my code? If you see any inconsistancies or bad practices in there.. just let me know so I can work on it before I dig myself a hole lol
sure, just use one of the links tho
the raycast ? then why is not working ?
Something in the logic is f**ky.. I have to hit spacebar twice to have the ball drop off the player.
assuming you never get to set current ?
currentInteract != null || currentInteractable != null
what do you mean
OH
wait what
is the item you instantiate the same interactable ?
hey, @rich adder i tried the coroutine but cant seem to find whats the mistake in my code. I want it so when the enemy hits a tower it reduces the health of tower. but I want the enemy to attack like every 1 or 2 second. I made a oncollisionstay2D but it instantly killed the tower,
yup
did you intend to write .lossyScale btw
where?
oh wait thats a thing
the line you highlighted
i got rid of that
I'll be back in like 15 minutes or so if you get a chance to look at that send me a reply. Thanks dude
i didnt need it anymore
this coroutine doesn't do anything right now
you need code inside
no you dont declare method inside it
o
does tower have a trigger collider ?
you can use onTriggerstay2d if you want an area of damage ? or do you want only edges
dont worry i just copied the wrong code but in my new code its stay
basically i just want it to damage once it collides with an object and wait for 2 seconds then attack again
hmm in that case you should only call coroutine if 1 is not running already
so what do i do now?
put a bool in the coroutine before and after the wait for seconds
put damage method after the waited seconds
alright
wait
do i add the void oncollisionstay?
below the wait for seconds
i made the bool
eg
private void OnCollisionStay2D(Collision2D col)
{
// put same towercheck here
if (attacking) return;
StartCoroutine(Attack());
}
bool attacking;
IEnumerator AttackTime()
{
attacking = true;
yield return new WaitForSeconds(time);
//Attack()
attacking = false;
}```
yo what theme is that
Looks awesome
🥁
its for VSC 
iirc you can import json themes from vsc to VS
yeah sadly
i tried installing unity with visual studio thingy but started giving me "Download failed" or whatever
oh u fr ill look it up ty
still doesnt work navarone
show current code
{
public int damage = 5;
private void OnCollisionStay2D(Collision2D collision)
{
if (collision.gameObject.GetComponent<TowerHealth>())
{
collision.gameObject.GetComponent<TowerHealth>().health -= damage;
if (attacking) return;
StartCoroutine(AttackTime());
}
}
public bool attacking;
IEnumerator AttackTime()
{
attacking = true;
yield return new WaitForSeconds(2f);
attacking = false;
}
}```
the enemy just kills the tower within like 5ms
your attack goes in the timer
you need to pass it Tower
i dont get it
private void OnCollisionStay2D(Collision2D col)
{
if(col.gameObject.TryGetComponent(out TowerHealth towerHealth))
{
if (attacking) return;
StartCoroutine(AttackTimer(towerHealth));
}
}
IEnumerator AttackTimer(TowerHealth towerHealth)
{
attacking = true;
yield return new WaitForSeconds(timer);
towerHealth.health -= damage;
attacking = false;
}```
🥣
if you want the first hit to happen right away just move the dmg part above seconds.
Yeah.. I am having to double tap my spacebar to get the ball to drop. Something is off in the logic. I am sure I will eventually find it. I'm sure it's something simple
hard to say without context 🤷
I'm sure I wrote this is a non optimal way..
where is the ball dropping
footballFollow position
you mean footballFollowing
The football is being enabled after being disabled
yeah
wait
at the bottom of the footballController code
bottom of the page
Pass?
Yeah pass (the space bar is supposed to drop it)
it does, but I have to tap it twice quickly while footballFollowing is disabled. It reEnables after short time
is it on a player its probably trigger again no?
I found the area with the issue I think
From the Ienumerator PickedUpFootball down.
And look at the Act() method
something in there is wrong..
maybe its that animator bool ? are you looking at it in the inspector how it acts
When I press spacebar once the footballFollowing is false.. and it switches back to true automatically
but if I hit the spacebar again inbetween when it switches back it drops the ball
is possible PickedUpFootball coroutine is called twice or something
will there be any problem if i have this active monobehaviour in builds?
this is a monobehaviour (got cropped
)
But you've got it to execute only in the editor
probably compiles out when you build
aint UNITY_EDITOR directive is precisely for that lol
Pretty sure it won't build properly
Assuming this GameObject exists on any object that isn't tagged as editor only
Hey, what is the point of this? Is it so I can access the GM from other classes through GM.instance? Is there any other reason to do this?
A singleton? Only one instance of the class can exist, so it's doing some checking to not make dupes
Two things:
- makes sure there's only one copy of this script in the scene
- Gives you a static reference to the one instance
Thanks
How can I make a tire go flat and have a physical re-flat?
Hi reasking about an issue i have since yesterday
im trying to make a gameobject active when pressing the Z key while the player is colliding with an npc.
the player does stop when the player's and npc's collider hits, but nothing shows up on console logs when they do, so pressing Z does nothing
went through the suggestion from @/boxfriend to use https://unity.huh.how/programming/physics-messages but none of the fixes there seems to be my issue
So.. i want to ask the standard troubleshooting questions, but it seems like quite a bit has been gone over already?
So just rapid fire:
1 The CharacterController is on one of the colliding objects?
2 Both objects have colliders, and neither are set to be a Trigger?
3 Both objects have a rigidbody2d?
4 The collision matrix isn't disabled between their layers?
5 Neither of the rigidbodies have layer overrides set to anything but "nothing"?
6 are either of the objects moving really quickly? You ARE teleporting, so this could be an issue
I haven't gone through the unity.huh.how guide for this throughly, but I'm sure all of that is covered there, sorry.
Having trouble getting these two scripts to work for my health pickup item in my game. It keeps giving me a "not set to instance of an object" error
thanks for the help
- the script i provided is attached to the player gameobject
- both the npc and player objects have boxcollider2d, neither is set to isTrigger
- only the npc has rigidbody2d
- both objects are on the interactableLayer, in proj settings there is a check mark between interactableLayer and interactableLayer
- i dont think so? all the settings are default except making the npc kinematic
- none of the objects are moving
I according to this graph, it looooks like both objects need rigidbodies?
https://unity.huh.how/programming/physics-messages/collision-matrix-2d
Edit: nevermind, it says at least one
it specifically doesn't like line 13 in the second script
do these events even run on kinematic rigidbody lol
Ontrigger and oncollision? Yes
One has to be dynamic, the other can be kinematic
Yeah, I know, I pointed that out. I am confused by the wording in vertx's page though. It says:
"A Collider 2D is required on both objects, and at least one object needs a Rigidbody 2D"
It's worth trying having an rb on both though for sure
That error means something is null, meaning it didnt find a health manager
Ah, I wonder if that ONE rigidbody is kinematic. Which would not work.
It maybe needs one, but it HAS to be dynamic?
Kinematic only works WITH dynamic, which basically means it doesn't work with kinematic lol. So you're right
I think OnTriggerEnter runs with kinematic+ rigidbody on either object and OnCollisionEnter runs with dynamic rigidbody on either
So, is that one rigidbody kinematic?
yeah
so i just change it to dynamic?
Hey, I seem to be getting a stack overflow, but can't figure out why.
When i debug the log, it spams this code 13953 times in one go, though it should only fire once? A separate coroutine is only enabling the collider for this to register ONCE within a window. This already works for weapons, but it's not working for this?
All the previous code is working, but when it hits "iDamage" interface, suddenly it breaks down and stack overflows. It's all debugging on one class too.
private void OnTriggerEnter(Collider other)
{
if (!other.CompareTag("Player"))
return;
Debug.Log("Called OnTriggerEnter!");
if (other.TryGetComponent(out IDamageable iDamage))
{
Debug.Log($"Damaged {other} + {iDamage}");
iDamage.TakeDamage(1);
}
}
The target class just has this, nothing special. Hasn't been an issue. Not sure why the interface is going crazy
public void TakeDamage(int amount)
{
TakeDamage(amount);
}
One of the two needs to be, yeah
all right thanks everyone
i’ll have to try that later since i dont have access to my computer atm
in ur TakeDamage method u call it again lol
if (!football.activeSelf) //if football is not Active
{
Debug.Log("Football Following");
{
FootballFollow(); //have football follow player
}
}
else (football.activeSelf)
{
}
why is this not ok?
I figured it out, I had the health manager script on an empty object and forgot to add it to my player
The empty object was just there to actually implement the health system beforehand
you should still add a null check, if its null just throw some error like $"{collision.gameObject.name} has no health manager but is tagged Player"
itll help if later on you have the same issue
whats not ok about it?
Was giving me an error. I needed to move it anyways. It's bettering within the Football Following method anyways
you should post what the error is whenever u have issues like that, the only thing i really noticed is that you have an extra {} for no reason around FootballFollow();
sorry
private void FootballFollow()
{
if (!football.activeSelf)
{
football.transform.position = following.transform.position;
}
else
{
football.transform.position
}
}
I know that isn't the proper syntax.. but using that I would like to place the ball somewhere in relation to the player. like a vector 2 or vector 3
let me retype this
That isn't my final code for the else statement. It is just where I am trying to think of how to do that
you would do the same thing you do in the if, which is assign it some value. But its up to you to determine what the value is, is following supposed to be the player?
well then it seems like you would just want to do following.transform.position again, but that would mean your if and else do the same thing
The football game object is disabled. while the player has the ball. Then it is enabled when it is dropped.
But the issue is.. if I drop it on my players location it just picks right back up
I won't always be this useless.. once I get rolling I won't have as dumb of questions lol
this sounds like a completely separate issue tbh, the if statement isnt needed since both if and else are gonna be doing the same thing. If you want to place it at some offset then that would be different like placing it 1 unit infront of the player
I have that method running in the update
so when the ball is enabled the if runs
and when it is disabled the else runs
TakeDamage calls itself, and there is nothing to stop it from doing that over and over until the game crashes
football.transform.position = new Vector3(following.transform.position + 5, following.transform.position,0);
I know this is an abomination.. how I know it doesn't like the + 5
position has an xyz, it doesnt know which one u want to add 5 to
following.transform.position(+5,0,0); just trying stuff at this point
used it like a method.. which is an error
i have a smoke particle system as a child of the enemy. when the enemy dies a random force is applied so it falls/rolls in a random direction. im having an issue where the smoke sometimes emits into the ground if the dead enemy rolled a certain way. i was thinking of applying a script to the GO with the particle system on it to keep it rotated in a favorable direction but not sure exactly what to do if someone could help me out? or is there something i could change on the particle system itself to behave the way i want?
https://docs.unity3d.com/ScriptReference/Vector3.html
you'll want to use the properties of it like position.x or .y or .z
What is the syntax.. new vector3 (following.transform.position x, following.transform.position y, following.transform.position z)
Perhaps some collision on the particles and add some bounce, but if it spawns inside of the terrain that will probably will need some adjustments outside of the system. Actually, could just force the the smoke into an upwards (world coords) direction and center the PS.
Thank you.
{
Vector3 stopFollow = new Vector3(following.transform.position.x, following.transform.position.y, following.transform.position.z);
football.transform.position = new Vector3(stopFollow.x + 5, stopFollow.y, stopFollow.z);
}
Am I on the right track with this?
you could just add 5 to the position.x inside the first line then not need to do new Vector3 twice
Vector3 stopFollow = new Vector3(following.transform.position.x + 5, following.transform.position.y, following.transform.position.z);
football.transform.position = stopFollow;
Thank you by the way
You could refactor with cs var stopFollow = following.transform.position; stopFollow.x += 5; football.transform.position = stopFollow;
Every call to Transform dot Position property returns a new Vector3.
Thank you , just looked uprefactoring.
I am about at the point of just scrapping what I have and starting over. I feel like my code should be more optimized.. and I feel like I have too much shit for what needs to be done. It should be wayyy way less steps than this
Want to see my code and tell me how much of a mess it is? Constructive critisism is welcome. I can learn from it
Premature optimization is unnecessary but refactoring of code could reduce length, create reusable patterns, and be more readable. Reduction in length is the lesser important of these.
I'm on mobile and won't be able to write code
Do you mind if I explain what I am trying to accomplish. It shouldn't be this involved for what simple stuff I am trying to do
Oh I don't mind. Don't need you to. Just curious of your thoughts
You'd just ask and all who visit here will look/reply if they feel like it. If you don't get responses, the question/problem/discussion may be too vague or complex (break it down or provide more context) etc
How correct is it to write code like this? Maybe you should make a nested condition?
public int _splatterCount;
private void Update() {
for (int i = 0; i < _splatterCount; i++) {
CreateBloodSplatter();
}
if(Input.GetKeyDown(KeyCode.R)) {
var random = Random.Range(1, 5);
_splatterCount += random;
}
}
public void CreateBloodSplatter() {
var splatter = Instantiate(_bloodSplatter);
splatter.transform.parent = transform;
}```
im trying to make a code that creates an object on the screen for every _splattercount there is
but this makes the loop go on infinitely
the loop is fine but you create objects in every update loop
When you put code in update it'll run every frame
You could fix this by using a boolean value, createdBloodSplatter, and only run that loop if that value is false. Once the loop is complete set it to true.
My god... I just spent 2 freaking hours.. wondering why my code wasn't working... and it turns out I had something like this
if (blah blah blah {}
{
the code..
}
I cannot believe that
sadly still doesnt work
assets for fps game pls
Unity asset store?
yea
No I mean go to Unity asset store
Nothing wrong with that
Less nesting feels cleaner to me
I'm sure they work for many people. Do you have a specific problem?
If i want to store a single value (for example, a string or specific script) in a gameobject should i use the variables component?
Isnt the variables component for visual scripting?
talking about this one
You can make a MonoBehaviour script and store your variables there
Yeah that is for visual scripting. Are you using that?
im trying it out, im asking to know if its more efficient to use this or to just make a new script to store the variables
No idea if visual scripting lets you access variables from a regular script
This channel is for C#. Which is more efficient that VS
And no, we dont use the variables component with C#, we put variables into script components instead
alright
can some help me?
when i interact the method ResetInteraction() gets called
the problem is that when i interact with something, in this instance im picking up an item
in HandleInput() i interact when i press f
and it debugs that its interacted
then it resets the interaction
but then then the raycast somehow still sets it again
which causes the text to now dissepear because the timer gets set again
its only when i split items
wait no its only when im stacking items
so its prob the order of execution
when i interact with my item the interact gets called
which then calls the pickup method
which calls the add method
which then calls the add method in the cell
thats when the item is not hitable by the raycast anymore because im setting it to now active
but when im stacking items it somehow runs faster?
YO.
So my onclick function is not finding my changebuttoncolor function which i made. How do i fix this? 🙂
Your component is not on the object you dragged in
i found out what the problem was
when i was adding to an existing stack
i was just destroying the item game object
because i was just adding the amount since i was adding to stack
but i just added item.gameObject.SetActive(false);
before i destory it
and the raycast doesnt detect it anymore
which is what i want
why?
if im destroying it, its not gonna be there anyways, so the raycast shouldnt set it again
or maybe the Destory gets called a second later than SetActive does?
In Unity, when you destroy an object using Destroy, it's not immediately removed from the scene. Instead, Unity marks it for destruction, and it will be removed during the next frame or at a later point when Unity's garbage collection system processes it. This means that the object still exists in the scene (albeit as a "to be destroyed" object) until it's actually removed.
thats why
alright
brainstorming sometimes helps
IDK if this is the right area to post - sorry. I have a large pixel art sprite, however using point and zero compression, the quality is a bit blurry. I have a solution for importing the sprite as sections but I want to know whether there is a way for it to be done on unity instead
hello
I need help
pls
my raycast does not hit the target
someone know how to solve it?
this is a code channel. try asking in #🔀┃art-asset-workflow
Thanks
could someone help me with weapon and animation shoot?
I am making 2D top down movement
code:
float vInput = Input.GetAxis("Vertical");
float hInput = Input.GetAxis("Horizontal");
transform.Translate(Vector3.up * moveSpeed * vInput * Time.deltaTime);
transform.Translate(Vector3.right * moveSpeed * hInput * Time.deltaTime);
the only problem is when i move diagonally it moves faster
does anyone have a fix for this
you'll want to create a Vector3 from your input and normalize that (or clamp its magnitude to 1 if you want to support moving slower for analog inputs that are not fully activated)
do you mind showing me an example
sorry i am new to coding
do you know how to create a new Vector3?
yeah
so do that and use the vInput as the Z axis and hInput as the X axis
then you can use that Vector3 .normalized instead of Vector3.up * vInput and Vector3.right * hInput
got it thanks
https://gdl.space/okikojabev.cpp why is the coroutine "Fall" tanking my DPS so hard?
FPS isnt whats supposed to be falling 
okay, I see now, debug.log took away my 150 FPS
is there a particular reason you're waiting for the end of the frame instead of just yield return null to wait for the next frame?
You would need to show your code
So I'm making a roguelike where you can choose a splitting path of rewards every time you beat a level however the rewards require you to go into a different scene and when you go back, the rewards are different, which I don't want to happen. Is there anyway I can recreate the rewards path to be the exact same as it was before. Here are the important parts of the script. I can post it all in a paste bin if you want to see it all.
public void CreateSplitPath()
{
Debug.Log("path creating");
for(int i = 0; i < numberOfPaths; i++)
{
GameObject gamePath = Instantiate(path, Vector3.zero, Quaternion.identity);
gamePath.transform.SetParent(pathArea.transform, true);
gamePath.transform.localScale = Vector3.one;
//gamePath.transform.localPosition = new Vector3(100 * (i + 1), -85, 0);
for(int j = 0; j < nodesInPath; j ++)
{
GameObject pathNode = Instantiate(pathNodeButton, Vector2.zero, Quaternion.identity);
string pathType = possibleScenes[Random.Range(0, possibleScenes.Count - 1)];
pathNode.GetComponent<GamePath>().sceneToLoad = pathType;
pathNode.GetComponent<GamePath>().path = i + 1;
pathNode.GetComponent<GamePath>().pathNumber = j + 1;
pathNode.transform.SetParent(gamePath.transform);
pathNode.transform.SetSiblingIndex(0);
pathNode.transform.localScale = Vector3.one;
pathNode.GetComponent<Button>().onClick.AddListener(delegate{OnNodeClicked(pathNode.GetComponent<GamePath>());});
pathNode.GetComponent<GamePath>().levelSelection = this;
pathNode.GetComponentInChildren<TextMeshProUGUI>().text = pathNode.GetComponent<GamePath>().sceneToLoad;
}
}
//Spacing();
}
public void Start()
{
level.CalculateStartingCards();
cardNumberText.text = "Number of Cards: " + level.startingCards.ToString();
turnsAllowedText.text = "Number of Turns: " + level.turnsAllowed.ToString();
nextLevelButton = GetComponent<NextLevelButton>();
nextLevelButton.nextLevelButton = GetComponent<Button>();
nextLevelButton.pathsUntilNextLevel = numberOfPaths + 1;
nextLevelButton.levelSelection = this;
if(pathNumber == 1)
{
CreateSplitPath();
}
else
{
}
DataPersistenceManager.instance.SaveRun();
}
Didnt read all that yet but you can use Random.InitState with a seed if you need the randomization to be the same
sorry, i read the docs and am struggling to figure out how to use this for my game.
i know its probs really simple but ima bit dumb
i see you call DataPersistenceManager.instance.SaveRun(); presumably to save the data that you need, right? so where do you load that data?
its loaded onsceneloaded in a datapersistencemanager script
okay so where do you access that data in this script to use it instead of overwriting it with new data?
or is that somehow completely unrelated to what you are trying to do?
i tried doing this but it doesnt seem to work
public void LoadData(RunData data)
{
currentPath = data.currentPath;
pathNumber = data.pathNumber;
pathArea = data.currentPathArea;
}
the path area is the place where the paths are and it should hold all the paths from before but it's just blank
then you need to look at what you are saving and how to make sure you are actually saving the data that you need
i think i see the problem, i just saved the game object to the data file, which wouldnt be the same as the one in the scene so it just wouldnt be able to create a path
however i dont know what other method i could use to save it to a file and reload it, do you have any method?
save the relevant data stored on the components, not the actual components themselves
ok ill try this ty
if i a have a structure in the hierarchy like this:
- A
- B
and the B object has script withOnEnableandOnDisablefunctions, but im only disabling objectAwill it also work?
- B
if not, how can i do that?
yield return null waits for the next frame?
well thats new to me
is there any difference?
okay thats double new to me
thanks
I assumed yield return null just.... doesnt wait, lol
so I didnt even consider looking up anything about it
WaitForEndOfFrame doesn't wait for the next frame, it waits for the end of the current frame, it just happens that the next time it is encountered it will be waiting for the end of the next frame. and every time you do new WaitForEndOfFrame() you're creating more garbage
so yeah, the reason is, I had no idea
and its good that I do now because I use this in every damn project
another thing about WaitForEndOfFrame, since you undoubtedly started the coroutine sometime during the frame before that condition would be met, it actually runs 2 loops in the first frame
that makes no sense to me
like, if I start in in the middle of a frame, it will just wait the half of the frame thats left, no?
https://docs.unity3d.com/Manual/ExecutionOrder.html
say you start your coroutine in Update. it runs until it hits the first yield. so it basically completes everything but the yield in loop. then at the end of the frame, the yield has completed so it runs again until it hits the next yield. then the frame progresses. so now you've completed the loop two times
@rare basin i don't know why you are reacting with the "it depends" react on that. that is how that works
or are you just salty that i suggested you try what you were asking about?
no, idc
well @slender nymph I think this single bit of advice will have the biggest impact on me down the line lol, not that it would be that crucial or something, but its something I wouldnt have even thought about, at least to me, the naming "null" just isnt very intuitive in this case
you're just returning null for each yield. so there's no condition for the yield to check so it just continues execution the next time the coroutine is updated (which happens every frame)
they probably set it up this way to avoid a lot of garbage creation because YieldInstruction (the base class for each of the types you can yield for a coroutine) obviously creates garbage when instantiated just like any other class
that's probably a poor explanation but i hope you catch my meaning
tried this but apparently it causes loads of unrelated errors for no reason
I´ll read up on it a bit more and Ill be fine
show what you tried and provide the errors
thats the issue of not having formal CS education, I sort of know how to use the tools but I dont know how they work under the hood, thus I miss stuff like this
i added this change
string pathType = possibleScenes[Random.Range(0, possibleScenes.Count - 1)];
pathScene.Add(pathType); // null reference error on this line
apparently that causes a null reference error?
also its spawning some of the path nodes in the wrong place even though i have a line fo code that sets the parent to the right thing, which is just really frustrating and makes no sense.
where do you initialize your pathScene list
what do you mean
if you parent some object, it doesnt snap to the paren't position
i mean that if that list is not serialized (by either making it a public field or marking it with SerializeField) then no instance of the list will be created so it remains null
if you want, you can set the localPos of the snapped object to 0
its in a grid layout group
hey, pretty simple question but my player movement right now is transforming along the global axes, how do i make it local to the players look position? so i move forward in the way im looking
transform.TransformDirection
nvm its because i thought that new List<string>() would eb the same as just writing null so i wrote null, lol im dumb
right now i’m just doing rb.AddForce(tgtMoveDir * addspeed, forcemode.force)
in that case you can just use AddRelativeForce
oh, simple
otherwise you would use the TransformDirection method i suggested before to convert the direction to be relative to the object's rotation
private void InitializeMesh()
{
meshFilter = GetComponent<MeshFilter>();
if (ringMesh != null)
{
DestroyImmediate(ringMesh);
}
ringMesh = new Mesh { name = "Arc" };
meshFilter.mesh = ringMesh; // this line right here, officer.
} ```
I need to make changes to a mesh through code in editor, however my console gets spammed with 'Don't do that in OnValidate'
What is the correct sollution for this - either to suppress the warning or what can I change to no longer proc the warning?
Don't tell me the obvious answer of 'Well just don't do that in OnValidate.' I need to update the mesh when inspector values change, in editor.
Well, you can tell me not to do it in OnValidate, if you also tell me where I should do it that will still function in editor 
Here's a way to suppress it
Scroll down a bit
Had a similar issue and it worked fine
checkin' this out now
private void OnValidate()
{
EditorApplication.delayCall += DelayedInitialization;
}
private void DelayedInitialization()
{
InitializeMesh();
CreateRing();
UpdateAnchoredObjects();
}```
delayCall worked great, thanks! 👍
sheesh, your right. I didn't even notice that obvious loop. I had an overload with the same name, and the interface and overload referencing was ambiguous. simple name change of the interface fixed it all
now it works, thanks!
Why I can' t add gameobject in scene to the script of prefab?
Prefabs cannot contain scene objects
Be careful with OnValidate. It gets called multiple times from the editor. Make sure to avoid the method being called multiple times . . .
what is the solution then?
Assign the reference in code at runtime
I don't understand. How to do that?
The = operator is used to assign variables
Usually you'd have the script that instantiates the prefab pass the reference to the newly created object
Some weird ass problems. The formula at the bottom works perfectly, but the codes above isn't being read at all, the "executing to turning to 0" debug log doesn't even appear
Your if statements make no sense
You're treating a quaternion as if it's a set of euler angles
rotation.y will never be greater than 1
And you shouldn't be touching it tbh. Never mess with individual quaternion components if you can help it, which you can
Much better to do something like cs if (Vector3.Angle(transform.forward, Vector3.forward) < 1)
okay, I'll try changing it
Also get in the habit of using else when appropriate instead of duplicating your if conditions
You probably even have a bug here where you'll fall into the second condition as a result of the code in the first
anyone could hewlp me ?
oh, yeah, and never check floats for equality
need help to attatck player with knife
hey, so whenever i jump, this script seems to zoom me in a random direction at super high speeds and im not sure why :c
void Update()
{
//Camera
transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivity, 0);
cam.Rotate(-Input.GetAxis("Mouse Y") * sensitivity, 0, 0);
//Movement
float multiplier = 1;
if (!isGrounded) multiplier = 0.5f;
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 * multiplier, ForceMode.Force);
else rb.AddRelativeForce(tgtMoveDir * addSpeed * multiplier, ForceMode.Force);
if (rbLateralVelocity.magnitude > tgtSpeed) rb.AddRelativeForce(-tgtMoveDir * (rbLateralVelocity.magnitude - tgtSpeed + addSpeed * multiplier), 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);
}```
Add some coloring please, its triple quote + cs
Not a direct answer to your question but you're doing AddForce in Update which is going to make your game behave differently at different frame rates. Physics should always be done in FixedUpdate
oh true, ty
Hello, I have a code that destroys a gameobject when it touches enemy. In the code I added a [SerializeField] so i can access variable from another script. but when i added more enemies instead of just one. The enemy destroys the game object and destroys the script I added to the [SerializeField] is there anyway to prevent that from happening
You should be instantiating from a prefab not from a scene object reference
And keep the instances in a List if you need to access them.
oh I made a prefab but I think i placed the thing from scene reference
