#💻┃code-beginner
1 messages · Page 531 of 1
this code may or may not have been copy pasted from somewhere on youtube, but i do understand the first part of this i just dont know why there is a second stop wall run
How do i get a raycast to ignore triggers? I dropped an object inside a trigger hitbox and couldnt pick it up anymore due to the raycast hitting the trigger instead of the object
after consulting with chat gpt I know what the second stop wall run does
Other than knowing what the functions do, you may sometimes want to see which function is being selected - log inside the conditional statements.
Google suggested: https://docs.unity3d.com/ScriptReference/QueryTriggerInteraction.html
Source: https://stackoverflow.com/a/44402600
I don't wish to sound insulting but why not try to use your brain instead of GPT
because then i wouldnt be 100% sure if i were right
But GPT can be wrong 
i was about to say that
and using GPT will definitely not give you that
Thus why it's avoided unless you know what you're doing but are simply leaving the heavy lifting to it or want to see what kind of monstrosity it would create.
true now that i think about it gpt could also be wrong
it still doesnt fix the issue that i couldnt trust that my assumptions on what it does are right
But it's very convincing and thus would have you playing mind games with yourself in the debugging of critical errors.
Looking at your code, if that came from a random yt tutorial, it is absolute rubbish
oh, what a surprise, more click bait
i mean i wouldnt say that
but you don't know enough to evaluate it, I do
fair enough
oh and btw regarding the question i asked you earlier about the dollar sign and you saying its neater, i agree but i learnt that from brackeys who alot of people think is very reliable
brackey is crap
I noticed in your Lerps, you are using Brackey Lerps which are just plain wrong
what do you mean plain wrong, like they dont work at all?
no, they kinda work.
Lerp is current = start, end, t where t moves from 0 to 1
you are doing
current = current, end, constant
An incorrect lerp that's commonly used/misused (it's not linear interpolation at all but some sort of scalar smoothing that never theoretically reaches it's target).
https://unity.huh.how/lerp/wrong-lerp
oh ok
what I hate most about Brackeys is that, even after having his code shortcomings pointed out to him over many years he could not be arsed to go and correct them
I'm trying to read a config .xml file into a list of objects for later use (Translating the list into a bunch of tuned objects), but when I run this script I get a pretty hefty "FormatException: Input string was not in a correct format". If someone has a bit of time to spare, please ping me, any help here is appreciated
BGHolder Class --> https://hastebin.com/share/bocubitalu.csharp
BGlayersConfig.xml --> https://hastebin.com/share/aculaderaj.xml
-# Extra Information
Defaults --> https://hastebin.com/share/perajagili.csharp ||(I know about the virtual issue)||
BGLayer Class --> https://hastebin.com/share/giyorimumi.csharp
-# I don't know the complexity of this, so it might not belong in this channel, tell me if that's the case
Have you tried logging the data (string) before the exception is thrown?
you mean Debug.Log(config)?
Show the full error (stacktrace)
one second
FormatException --> https://hastebin.com/share/owugolutuh.vbnet
here @ivory bobcat
So the error line would be
DefaultJrlGameObject.PathToXmlObject[T] (System.String relativeFilePath) (at Assets/Scripts/Defaults.cs:59)
Which would be the virtual function ```cs
virtual protected T PathToXmlObject<T>(string relativeFilePath) {
string fullPath = Path.Combine(Application.dataPath, relativeFilePath);
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (FileStream stream = new FileStream(fullPath, FileMode.Open)) {
return (T)serializer.Deserialize(stream);
}
}```where you weren't able to deserialize the stream.
Where it stated that
There is an error in XML document (33, 5)
line 33?
Maybe check out your xml file and see if there really is something incorrect there or not.
seems to me that the xml is proper, maybe the XMLBGLayersConfig is wrong, but that also seems fine to me
I sent them in the message, maybe you can see something odd
With only the first background layer within the xml script, are you still able to reproduce the error?
The main differences between the two that I see outright would be the second using negative values and the color field being 8 hexadecimal values instead of 6
Big brain moment hopefully
something weird happens
when there's only the first one, there's no error, when there's only the second, there is, when I paste the same values to the second one there's also an error, and when there's only the second with the same hex color as the first one, there is an error
I'll write it down:
#1 alone - no error
#2 alone - error
#1 and #2 with #1 values - no error
#2 with #1 color - error
Not sure. Maybe the serialization doesn't accept more than one background layer. Try a duplicate layer for the second layer (I don't know much about serialization or rather what exactly you're trying to serialize)
it's meant to work with alpha values in the color, negatives in the X,Y areas and multiple BGLayers
yeah the problem lies in the second one
Can't fit a square into a triangle (assuming both have the same radius, relative to shapes)
It's the X being negative
the color is fine
Man this is weird
why can't it read the negative X but reads a negative Depth just fine
It would depend on the type you're trying to serialize it as - XMLBGLayersConfig
that just has a list of BGLayers
So a unity Vector2 field.
Not sure why it wouldn't let. Maybe serialize a bg layer as xml and see how it handles negative values 
I don't get it
wwait maybe it's a negative float causing issue
IT'S A FLOAT
maybe eureka
hold up there's no error
give me 2 minutes to test something
You've got all of the time in the world. There are plenty of folks here who're listening and may comment on an issue. Keep at it and good luck.
thanks for the help mate
hallo
do i have to rewrite the whole code again just for walking and running animation?
void Update()
{
verticalInput = (Input.GetAxis("Vertical"));
horizontalInput = (Input.GetAxis("Horizontal"));
jumpInput = (Input.GetAxis("Jump"));
transform.Rotate(Vector3.up * horizontalInput * speed * Time.deltaTime * turningSpeed);
transform.Translate(Vector3.forward * verticalInput * Time.deltaTime * speed);
transform.Translate(Vector3.up * jumpInput * Time.deltaTime * jumpheight);
}
hello, i have a problem and idk what can i do to resolve this. So, I can't put with drag and drop from idle to controller.
Not a coding question nor is that a game object with a runtime animator controller
how can i add an runtime animator controller ?
so i put tilemap collider but it seems to not be working
anyone know a guide to do it in unity 6 or no?
What's the issue?
well the white box does not collide with tilemap
Unless the tile map moves, you can opt to remove the rigid body component from the tile map.
Does the white box move?
Can you show it's inspector?
Does the white box have a collider?
Well, try giving it one
hi i recantly learned how to change the position of the collider along an animation but it takes a while moving it in each frame is there any way to do it faster?
how do you do this? im still a bit sleepy i feel im missing the obvious
essentially having a factory create a GameObject with a script on it, then trying to assign that script to this.gameObject
I think you have some kind of misunderstanding, you can't have the same instance of a component on multiple GameObjects
you would need to instantiate a new Settler on this gameobject and then clone thisSettler into it
Does coroutine yield return new WaitUntil(() => variable); return at this point or does it continue after the line?
Is there a way to stop coroutine from going further like break?
It'll continue after the condition is successful, you can use yield break; to exit the coroutine immediately, similar to using return; in a regular method
You cannot do that from inside the lambda expression though, as it's not a coroutine
Makes sense, thanks
hey ppl, im having some trouble with LOD that looks like my culling distance is restoring the full mode
anyone knows why?
here i disabled most of the renders in LOD
this is when it hits culling distance
If you are not controlling the LOD by code, you're better off asking in #💻┃unity-talk
Else, show the code!
sorry, untiy talk looked more like genral chat. i was nto sure about say it there
I'm making multiple usable objects via OnTriggerEnter CompareTag.
I want those objects to be deactivated when you use them.
How do I refer to the exact object that I'm using, instead of deactivating them all via Tags?
If you 'make' objects using Instantiate it returns the 'made' object
😭 i got ignored
again
hallo
do i have to rewrite the whole code again just for walking and running animation?
void Update()
{
verticalInput = (Input.GetAxis("Vertical"));
horizontalInput = (Input.GetAxis("Horizontal"));
jumpInput = (Input.GetAxis("Jump"));
transform.Rotate(Vector3.up * horizontalInput * speed * Time.deltaTime * turningSpeed);
transform.Translate(Vector3.forward * verticalInput * Time.deltaTime * speed);
transform.Translate(Vector3.up * jumpInput * Time.deltaTime * jumpheight);
}
I'm not using Instantiate. They're are placed on their spot
then why say 'I'm making multiple usable objects via OnTriggerEnter CompareTag.' ?
:/
How to normalize scale of a sprite? I currently have [2.1111, 2.1111, 2.1144], how do I turn it into [1,1,1] while conserving the same size
can anyone plz help me
aham.....
Move the SpriteRenderer to a child object and scale that instead, and/or change the PPU on the image import settings
Not a code question though
I mean that they're are used via OnTriggerEnter CompareTag.
They're are not spawned via TriggerEnter
then, surely, you already have a reference to them
what is that u want? someone to help u rewrite ur code?
look up a tutorial on how walking and running animations work and you'll find out. but i'd rewrite the code anyways because with transform.Translate you won't collide properly with walls and stuff
^ facts, use rigidbody functions.. or switch to a character controller and use Move()
is it possible to fix this? Thanks
So if the error is on TerrainData why are you showing TerainGenerator
also !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.
Sorry, first time
Also TerrainData is a Unity class, you really should not have your own with the same name
umm im getting this error until I open the object in the inspector, then the issue disappears for that instance
any clue at all what this could be
im working with a group mate's bit of code so its a lot harder for me to debug
my best bet is something to do with [System.Serializable] maybe
Hey everyone, when I try to instantiate prefabs, they don't animate. They instead stay in their Idle animation, even when I mess with the blend tree manually.
Here's my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnEnemies : MonoBehaviour
{
public GameObject Enemy;
public int XCoord;
public int ZCoord;
public int EnemyCount;
// Start is called before the first frame update
void Start()
{
StartCoroutine(EnemySpawn());
}
IEnumerator EnemySpawn()
{
while (EnemyCount < 10)
{
XCoord = Random.Range(10, 20);
ZCoord = Random.Range(10, 20);
Instantiate(Enemy, new Vector3(XCoord, 0, ZCoord), Quaternion.identity);
yield return new WaitForSeconds(5);
EnemyCount++;
}
}
}
Any thoughts on how to remedy this? Thanks!
there is no code to animate anything there
oh shoot, one second, sorry
This just spawns objects. What is supposed to animate them
my best bet is something to do with Scripts/Systems/UIManager/Tests/SettlerPanel.cs
specifically on line 51
thanks
any idea why the issue is tied to opening something in the inspector at runtime?
As it's a runtime error I fail to see how it can be generated by opening an inspector
its almost like it cant see the value until i open the object in the inspector
its really weird ill see if i can record it
here
whats also weird is some information like the name and some others work fine, it usually throws the error when it gets to health or attack
how is this weird. there's just an error in your code
is the error coming from one of the lists?
what lists?
are you gonna investigate where the error is coming from and fix it?
or did you just post it here as a show off
chill out dude I've already tried to fix it and ran out of ideas which is why I'm asking for help
sorry i thought you didnt want help because otherwise you would have shown us the script by now 😭
I'd rather not show the script since it is a friend's work and I can't ask for permission right now
then at least show line 51
its line 71 now as I split something into two methods, but its the same error
it seems it has absolutely no issue until it gets to values.stats.attack which then throws a nullreference
so values.stats is null
but then why would they suddenly not be null when opened in the inspector
because they are being initialzed somewhere else
the inspector initializes it
opening in the inspector has absolutely nothing to do with it
hello. I have this issue with my jumping animation. It's working when the character is not moving, but when I move (ignore the character sliding left/right/back, I will work on it later) to any direction, it barely jumps
seems youre right
I am still starting out and unsure thats why I am asking. If the bool is ture does the code run or does it just always run?
Always runs
Okay thanks
This will print "true" or "false" in the console, depending on the value you passed to this method
ok i managed to fix it after generating my own SettlerStats when creating the Settler, thanks for the help
Sorry for needing help again. I got one program which declares and adds values to the int stars. In a different program I want to access the value of stars and I dont know how, does anyone have an idea on how I could achieve this?
wdym by program
2 different CS files
so 2 different classes
Yeah
see the pinned messages here under General
What can be reason they dont collide? I did debugs they were colliding but they dont effect each other.
also anybody have any idea for detecting damage? When I hold my sword to block enemys sword, because normally enemy runs to me , he collides with my sword and takes damage
maybe this could be a reference for what I want
how do i save a dictionary with keys being strings and values being bools using a binary formatter?
Never use binary formatter
It's obsolete and should not be used
It is unsecured and cannot be secured in any way
Whenever this function is called, it will print the string representation of the bool you have passed to it
Reference the instance that has the value you want
https://unity.huh.how/references
Choose the best way to reference other variables.
I read some stuff of it but didnt understand it because I am stupid and then gave up because I am too afraid to ask again how to do it
Well if you've already decided you're too stupid to try then there's no point in continuing
But here we go again I suppose. I got this class with the int Stars and I want to get the value of stars in a different class
int is not a component
im losing my mind
Yeah understandable :c
how to save/load dictionaries using json serialization?
I have 2 gameobjects. Both of them have 2D Colliders. One of them has a "IsTrigger" on them, the other one (the one supposed to be destroyed) has the correct tag but nothing happens. i feel like im having tunnel vision
The Three Commandments of OnTriggerEnter2D:
- Thou Shalt have a 2D Collider on each object
- Thou Shalt tick
isTriggeron at least one of them - Thou Shalt be moving via a 2D Rigidbody on at least one of them
are those two screenshots from different classes and you want to call AddIncome from UpdateSquare or what?
RIGIDBODY I FORGOR
Yes they are from 2 different classes and I want the value of stars in the other class (The one with income)
So you would reference the class that has the value you want
Well the only way I have learned it so far is putting static in front of the class to then refer to it but I was told not to do that
like the line "public TMP_Text counter;" where you reference the TMP_Text class. thats how you reference other classes
that's not a reference
You should look at the thing I linked
Will do
Like this?
or without public
im tweakin. now they have rigidbody2d but they still dont work 💀
yes now assign it in the inspector like you did with the text
How are you moving the object
They dont have movement yet, so i start the scene and move em manually.
So then they aren't moving via a rigidbody
It should still work. It worked B4 with player and enemies system.
I feel like im missing something extremely simple.
Show the inspectors of both objects involved in the collision
Object i wanna destroy. Object which should be the destroyer.
Static rigidbodies do not move, and therefore do not collide
Other rigidbodies can collide with them
But a rigid body needs to be moving, as per commandment 3
If its not static it would fall to the void. ill make a quick base floor quick but it still wont work
im losing all faith. all hail 3D
You need to just not half ass it and actually implement a rigid body
It worked 💀
Bad habit. My bad. But i swear the player triggers did function before when i did the same.
Rigidbody calls all of its collision functions when it moves into a collider
If a rigidbody is not moving, the functions don't get called
static rigidbodies do not move
I know but.
So, therefore, a static rigidbody cannot move into a collider
Yeah nvm. Now i see why my question was dumb 💀 thanks again g.
I should have used gravity 0 instead of changing it to Static.
how can i make this json save system save dictionaries? it saves other data types perfectly fine but for some reason the dictionary i want to save doesnt get saved through this system and resets back to its default values
https://hatebin.com/nmbhbnefeo
Dictionaries are not serializable, so you'll need to use a different data type. Consider two lists, and have them combined into a Dictionary when you load
What's the proper way to do mobs? I know it depends, but still. The tutorials I'm seeing seem either too simple or too complex. I'm trying to make something dynamic, since I'm making animals, like bunnies, deer and dogs, but I'd like to make bosses too while reusing as much code as possible. Is it really necessary to make a script for each creature?
okay, one question, how would i add each element of the two lists into the one dictionary? like for lists there's stuff like myList.Add() but what abt for dictionaries?
You are probably never going to find a tutorial that just does exactly what you're looking for. This is why you learn the concepts behind them and then apply them to your own needs
dict[Key] = 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.
okay, ive done that but for some reason now my game doesnt save and its giving me a NullReferenceExceptionError when i exit the game??
https://hatebin.com/mqdjjosahy it refers me to line 11 of this script which is where i make the string list and bool list to then merge later on into a dictionary
and over here at line 28 https://hatebin.com/qtaemejuty when i make a new PlayerData
line 11 cannot throw a NRE, however the variable on line 11 is null because you don't assign it anywhere
what you could do instead of that foreach is just do FlagNames = GameManager.Instance.flags.Keys.ToList(); and do the same for the FlagValues and the Values
yes it seems so but im not sure how? i probably shouldve mentioned this but i have a script for the player which has its own method that retrieves saved data. i made a for loop that sets the flag values to the saved flag values so how is it still null? (below is the for loop im talking abt for reference)
for (int i = 1; i < GameManager.Instance.flags.Count; i++)
{
GameManager.Instance.flags[data.FlagNames[i]] = data.FlagValues[i];
}
the variable on line 11 is null because you don't assign it anywhere
i thought i was assigning it in this line, no? FlagValues = GameManager.Instance.flags.Values.ToList();
actually hold on
now point to where you had that line before i told you about using it
this? FlagValues.Add(pair.Value);
that does not create an instance of the list. which is why it is still null. that is the line that is actually throwing the NRE
ohh okay
again, you have to actually assign to the variable somewhere or else it will be null
actually sorry im a bit confused. my line didnt create an instance of the list. so i have reqritten my code to this.
FlagNames = new List<string>();
FlagValues = new List<bool>();
foreach (KeyValuePair<string, bool> pair in GameManager.Instance.flags)
{
FlagNames.Add(pair.Key);
FlagValues.Add(pair.Value);
}
now for actually assigning the FlagValues variable, im confused on where exactly im supposed to be assigning it?
those lines that you just added are assigning
or you could erase all of that and use what i suggested
by "erase all of that" are you referring to the foreach loop or the entire code block i pasted rn?
google what the definition of "all" is
📃 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.
@silent okay i've done that, and when i save the game the value im working with is true which is what i want, but still when i load the game again the value goes back to being false?
now show how you have determined that as well as where you call the LoadPlayer method
But why does it work with the other? They are the exact same
show where you actually assigned to the variables
I dont do it for both...
but one works
you have assigned one of those variables somewhere. probably in the inspector, but that is just a guess
With your eyes, Bert
I did but I did it for both
prove it. show the entire class and where you've assigned it
Okay so where do you assign these
-# idk
But why does one work then?
do you even know how to read?
Until you actually show where you are assigning them, this cannot be answered
Does anyone know how i fix that Visual Studio is detecting the Unity functions as unreachable code and fades them out?
Well this is all the code I have, I just have some objects and thats it
So, show where you assign the variables
!IDE 👇
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
I am sorry for causing such stupid mistakes, I have just started out, I forgot to assign it here:
I appreciate you help and patience
if only you had bothered reading this: #💻┃code-beginner message
I did check but I checked in the TMP_Text "income" and "counter" but not in the canvas, because I didnt know where they even get assigned
I followed a tutorial for the first one
i did that, visual studio is also having the functions tagged with "unity message" but still is fading them out
at this point you need to stop whatever it is you are doing and actually go learn the basics. if you don't know the basics of c#, then start with the beginner courses pinned in this channel. then afer you learn that, do the essentials and programmer pathways on the unity !learn site
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
how can i fix out greyed out code in unity its happening in all of my projects and no matter what i try i cant fix it
i just asked the same xD
I watched this tutorial about C# https://www.youtube.com/watch?v=wxznTygnRfQ
C# tutorial beginners full course (C# for Unity)
#C# #tutorial #Unity
⭐️Time Stamps⭐️
#1 (00:00:00) C# tutorial for beginners 🚀
#2 (00:06:30) output 💬
#3 (00:10:48) variables ✖️
#4 (00:19:32) constants π
#5 (00:20:35) type casting 💱
#6 (00:27:49) user input ⌨️
#7 (00:31:24) arithmetic operators 🧮
#8 (00:35:54) Math class 📏
#9 (...
but never watched one about Unity
which I should do
congrats. please read the full message instead of stopping halfway through
Yes I will do that too I just didnt mention it
then make sure all of the relevant packages and stuff are up to date, including visual studio. and regenerate the project files to see if anything changes
im sure everything is upto date its just that i did something with intellisense that broke it
idk i have a fresh install of everything on this pc
i found a ticket for it in the MS system it seems we didnt do anything wrong, we just have the newest versions that are broken
https://developercommunity.visualstudio.com/t/Private-Unity-messages-incorrectly-marke/10779025
yeah i cant find any fixes i might be cooked
How would I get my enemy to jump over a gap/pit?
i might be cooked
by a visual bug that barely impacts your workflow at all?
where i should ask for support on why my 3D model isn't placing corectly on a grid? (i m trying to make a building sistem fallowing up Sunny Valley Studio's tutorial)
idk what is my problem exactly, code or just 3D procesing 😦
then ask your question in whatever channel it is you think is most relevant to your issue and provide actual details
firstly this is what i imported as a .obj file:
TF I SOLVED THE PROBLEM JUST BY CHANGING THE Z OF THE 3D MODEL
ty anyways
by changing the z of the 3d model
or do you mean by changing the Z axis on the child object of the prefab so that it lined up exactly with the parent object which is what you were placing?
exactly!
Hey what program language does unity use? i forgot
you can also use
to find information
ok thank you for the help 😀
isn't that the same as C++
Hmmm? ok
Can you tell me what the difference is because they came from the original C program
a ton of stuff came from C. doesn't mean that they're the same
They're two different languages. They have similarities, but ultimately they're different.
google should be able to tell you their differences
Ok thank you because I'm learning from Codecademy
i'd be willing to be that most of the languages you've heard of were probably based on C. that doesn't mean that they are all the same
someone please help im stuck in a lot of spaghetti
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
help me pls its driving me nuts!
have you tried restarting the editor
yep they keep coming back
okay so its a top down plane shooter game and im implementing an archetype system with passive skills and abilities and shit. its like a skill tree system where you can unlock more skills after unlocking the ones prior. im getting really burnt out just with the skill interface menu and shit.
So theres 4 classes that are responsible for my skill system
PlayerSkills (singleton) - holds all skills and handles their activation
TreeManager (singleton) - manages the trees activation
SkillTreeManager - handles the SkillTreeScene and some UI in it
SkillNode - script given to each skill in a tree (UI button)
How it works is in a panel, theres 2 skill trees that cant both be activated at the same time, so if one is activated all the other skills in the other tree should be deactivated.
The skill nodes that are activated, but then deactivated due to activating another tree are remembered and reactivated when their tree is reactivated.
The issue -
When i start the game and go into SkillTreeScene, both the trees are deactivated on start. then when i click on one of the trees, and unlock some skills in it, then go back to another scene, then go back to SkillTreeScene, it remembers them just fine. but when i select one tree, then select another tree (deactivating the first one and all its skills) and exit the scene (SkillTreeScene) and reenter it, it forgets every single skill that was active, even though these skills are being stored in the singleton PlayerSkills.
DM me and i could show you pictures and videos of the error
for some reason when i jump my character kinda teleports upwards and also he falls super slow to the ground
here is the script
public class PlayerMovement : MonoBehaviour
{
public float speed;
public float jumpForce;
[SerializeField] private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
rb.velocity = new Vector3(Input.GetAxisRaw("Horizontal") * speed, 0, Input.GetAxisRaw("Vertical") * speed);
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
rb.AddForce(0, jumpForce, 0, ForceMode.Impulse);
}
}
}```
you're setting the y velocity to 0 in fixedUpdate
you'll want to avoid that and let gravity control the y velocity
so how do i do that
you could just set it to itself, ie replacing 0 with rb.velocity.y
or you could extract out the velocity first, and then set only the x and z values, leaving y untouched
i thought it was something like current.position or something
and i couldnt remember what it actualy was
thank you so much
Vector3 vel = rb.velocity;
vel.x = ...
vel.z = ...
rb.velocity = vel;
actually desperate someone please help me
It sounds like an issue with reapplying the persistent data to the objects in the scene. Are you doing that properly?
Hey, I have a game with audio mixers, where I use SetFloat in Start() to set their initial volume
It works for my background music that is played in the menu, but not for sounds that are only played in the main scene
I found this topic that sounds similar to my problem: https://discussions.unity.com/t/audiomixer-volume-setfloat-on-exposed-parameter-doesnt-work-when-mixer-inactive/813786
And this point sound relevant: After you play a sound on the mixer it gets active and you must then initialize the values?
If it's the issue, is there a way to "force" an audio mixer to be active?
Hey, does anyone know how to I would make a 3D dash using a character controller for the player on a button press? I got the input registered to a dash method, but I don't know how to make the charactercontroller move a certain distance over a duration, I only got it to move the distance in an instant.
you could set it at a certain (higher-than-walking) velocity for some period of time
how to make the charactercontroller move a certain distance over a duration
This involves doing something over the course of multiple frames. You will need to either start a coroutine, or track some state in variabels and deal with it in Update.
Thank you I ended up changing the speed which worked
Can I download a GIt repo through the Asset Manager window if the Git repo doesn't have a Manifest file?
While still being able to update the package through the package manager?
It needs to be set up as a upm package
Will I be able to setup updates via the Unity package manager with this?
yes
Those methods are called by Unity, and have signatures that are incompatible with UnityEvent
https://unity.huh.how/unity-events/method-requirements
If the method has a parameter, it must be either a:
float
int
bool
string
UnityEngine.Object (or an inheriting type)
People, the code has already been fixed, but there is another problem: the button is not activated.
!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.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Do you call ActivarBotonSalir anywhere
This button is already active but when the player gets on the button is deactivated instead of activated.
It appears to deactivate the button in Start, and activate them whenever you call ActivarBotonSalir
using UnityEngine;
public class DiceThrower : MonoBehaviour
{
public GameObject dicePrefab; // サイコロのプレハブ
public Transform spawnPoint; // サイコロの生成位置
public float throwForce = 0.1f; // 投射する力
public float throwAngle = 45f; // 投射角度
private GameObject dice; // 投射されたサイコロ
private Rigidbody diceRb;
void Start()
{
// サイコロを生成
SpawnDice();
// 5秒後に力を加える
Invoke(nameof(ApplyForceToDice), 5f);
}
void SpawnDice()
{
if (dicePrefab == null || spawnPoint == null)
{
Debug.LogError("Dice Prefab または Spawn Point が設定されていません!");
return;
}
// サイコロを生成
dice = Instantiate(dicePrefab, spawnPoint.position, Quaternion.identity);
// Rigidbodyを取得または追加
diceRb = dice.GetComponent<Rigidbody>();
if (diceRb == null)
{
diceRb = dice.AddComponent<Rigidbody>();
}
diceRb.useGravity = true; // 重力を有効化
diceRb.isKinematic = false; // 物理演算を有効化
}
void ApplyForceToDice()
{
if (diceRb == null)
{
Debug.LogError("Rigidbodyが見つかりません!");
return;
}
// 投射方向を計算
Vector3 throwDirection = CalculateThrowDirection();
// 力を加える
diceRb.AddForce(throwDirection * throwForce, ForceMode.Impulse);
Debug.Log("AddForce applied. Direction: " + throwDirection + ", Force: " + throwForce);
}
private Vector3 CalculateThrowDirection()
{
float angleRad = throwAngle * Mathf.Deg2Rad; // 角度をラジアンに変換
float x = Mathf.Cos(angleRad); // X成分
float y = Mathf.Sin(angleRad); // Y成分
return new Vector3(x, y, 0).normalized; // X方向に投射
}
}
I want to create a script that throws dice.
I succeeded in generating dice in advance and flying them.
However, when I tried to generate dice and cast them in the script, a problem occurred.
For some reason, a huge force is applied to the dice and they fly off into the distance.
I adjusted the air resistance numbers, but it made the problem worse.
For reference, if you create the dice in advance and throw them, the projected power is 4.
!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.
Is this okay?
You didn't post anything
Can you see it?
using UnityEngine;
public class DiceThrower : MonoBehaviour
{
public GameObject dicePrefab; // サイコロのプレハブ
public Transform spawnPoint; // サイコロの生成位置
public float throwForce = 0.1f; // 投射する力
public float throwAngle = 45f; // 投射角度
private GameObject dice; // 投射されたサイコロ
private Rigidbody diceRb;
void Start()
{
// サイコロを生成
SpawnDice();
// 5秒後に力を加える
Invoke(nameof(ApplyForceToDice), 5f);
}
void SpawnDice()
{
if (dicePrefab == null || spawnPoint == null)
{
Debug.LogError("Dice Prefab または Spawn Point が設定されていません!");
return;
}
// サイコロを生成
dice = Instantiate(dicePrefab, spawnPoint.position, Quaternion.identity);
// Rigidbodyを取得または追加
diceRb = dice.GetComponent<Rigidbody>();
if (diceRb == null)
{
diceRb = dice.AddComponent<Rigidbody>();
}
diceRb.useGravity = true; // 重力を有効化
diceRb.isKinematic = false; // 物理演算を有効化
}
void ApplyForceToDice()
{
if (diceRb == null)
{
Debug.LogError("Rigidbodyが見つかりません!");
return;
}
// 投射方向を計算
Vector3 throwDirection = CalculateThrowDirection();
// 力を加える
diceRb.AddForce(throwDirection * throwForce, ForceMode.Impulse);
Debug.Log("AddForce applied. Direction: " + throwDirection + ", Force: " + throwForce);
}
private Vector3 CalculateThrowDirection()
{
float angleRad = throwAngle * Mathf.Deg2Rad; // 角度をラジアンに変換
float x = Mathf.Cos(angleRad); // X成分
float y = Mathf.Sin(angleRad); // Y成分
return new Vector3(x, y, 0).normalized; // X方向に投射
}
}
I want to create a script that throws dice.
I succeeded in generating dice in advance and flying them.
However, when I tried to generate dice and cast them in the script, a problem occurred.
For some reason, a huge force is applied to the dice and they fly off into the distance.
I adjusted the air resistance numbers, but it made the problem worse.
For reference, if you create the dice in advance and throw them, the projected power is 4.
Yes
Plese help it...
What do you see printed in the console?
the skill nodes are being given their isUnlocked value on Start() based on the current values of the skills dictionary in the PlayerSkills singleton, what else?
it is console
I can't comment anything without having the project in front of my eyes.
But it should be trivial to debug. Add logs or step through the code to see if it's executed as you expect.
on it
Try reducing the force. The dice is very small and lightweight, so force of 5 is probably enough to launch it into space.
I tried changing it in the range of 0.1-0.01, but it stayed the same and flew into space!
If I drag & drop the prefab directly into the Hierarchy without scripting the dice, I can throw it with a force of 4 just fine.
like this
it is force of 4
If you generate dice with a script, it won't work.
I wonder why
Compare all the object properties from when you generate it via script and when you don't.
OK
I will Try
Also, maybe don't do Invoke see if the issue occurs if you call it from fixed update once.
But may be same one
Because copy both...(´;ω;`)…
Originally it was running without Invoke, but it flew to the moon
I guessed that it was a bug where force was applied immediately after generation, so I decided to wait a while after generation.
Hi, i tried to make an enemy wander, but something went wrong, it just...stands in there...frozen... why?
this is the code:
public class tuetue_script : MonoBehaviour
{
public int rutina;
public int cronometro;
public Animator ani;
public int direccion;
public float speed_walk;
public float speed_run;
public GameObject target;
void Start()
{
ani = GetComponent<Animator>();
target = GameObject.Find("Valeria");
}
public void Comportamientos()
{
ani.SetBool("tuetue_run", false);
cronometro += (int)(1 * Time.deltaTime);
if (cronometro >= 4)
{
rutina = Random.Range(0, 2);
cronometro = 0;
}
switch (rutina)
{
case 0:
ani.SetBool("tuetue_walk", false);
break;
case 1:
direccion = Random.Range(0, 2);
rutina++;
break;
case 2:
switch (direccion)
{
case 0:
transform.rotation = Quaternion.Euler(0, 0, 0);
transform.Translate(Vector2.right * speed_walk * Time.deltaTime);
break;
}
ani.SetBool("tuetue_walk", true);
break;
}
// Update is called once per frame
void Update()
{
Comportamientos();
}
}
}```
Add logs to see if your code is executed as you expect it to.
sorry for my ignornace, but how
Debug.Log()
Check the documentation.
Random.Range is exclusive max when using ints, so it will never return 2
Hey guys not sure but that seems to be related to the code of the buttons UI that I didnt do anything and suddenly appeared.. any ides?
never touched that in my life..
out of a sudden this happened and even if I close and open wont fix.
It's like a random editor UI bug. Try resetting the windows layout and clearing the error.
Reset .. closed all .. opened again
still the same 😦
hope I didnt lose my 3 months work haha
Why would you.
Try deleting the library folder.
Looking at the callstack it seems to be related to an ordered list. Does it happen when a specific object is selected in the inspector?
no.. if I open the unity the error is already there. That happened first time when I hit play in the game, and clicked in one of the button.
but now just opening the unity the error is already there
Very weird.
if I click in any button now I cant select the button action it wont open the dropdown
if I click here nothing happens
What components does the UserInterface object have?
Does it happen if you replace it with any other object?
hmm it fixes the prob if I dont use the UserInterface.. ok i will check further..
Does it have any components with broken references perhaps?
it seems like one of my components for some reason is like that now:
Will remove it now and might fix but have no idea how that happen.
that fixed the prob.. thank you
then how do i fix it?
the actor doesnt have gravity, i mean, doesnt fall, and its static, like when i just made it
Like if were just a plain draw on the plane
what do you think?
if 0,2 will not produce 2 then you need 0,?
Hello! Does someone know what is going on here? Of course, I have installed correctly the TextMesh Pro package correctly and since yesterday it didn't give any problem. Also, when I run the game in editor, the console doesn't show any errors and the game runs just fine.
replace it with 2, i guess
but...are u sure thats all? Im gonna check later cuz im not currently at my pc and is early
you already have a 2 there
do you never read documentation?
I mean, i dont even know of the existence of the objects, i just follow tutorials and analyze for myself how it works
sorry...
go and read the Random.Range documentation
in fact, when you know so little, 90% of your time should be spent reading the docs
make sure you don´t have errors in any other script and restart your editor. if that does not fix try to click on the underlined TextMeshProUGui and select a recommended fix in VS
regenerate your project files
thanks, I will try
regenerate project files means what
in preferences > external tools, you can choose to regenerate .csproj files
but I'm trying bot to restart editor and then regenerate those files
oh okay thought regenerate the library folder
this
allright
it still gives me error..
also, I tried what VS suggests, but it just suggests to delete them
is the using still underlined?
yes
post the assembly-csharp.csproj file to a paste site
it is really weird, just yesterday I made a build of the game and it didn't give any errors
today I open Unity and this happens
I'm thinking, maybe I could try deleting library folder and open again the project
you could try it in a fresh project and see if it is also giving the same error
ok I tried deleting: Assembly-CSharp.csproj file, Library folder, .vs folder, .vs config file, questiquest.sln file (game name). Then restarted Unity Hub and opened Editor. Problem solved.
If any of you ever faces this issue, this worked for me
nice
anyway thanks you all for trying to help, I appreciate a lot
that is the equivalent of cracking an egg with a sledgehammer
yeah!
but when opening editor and making a build again, it seems regenerates again those files so it's ok i guess
Guys why are my start and update functions greyed out
bug in latest VS
what do i do? downgrade?
you can rollback the update or look here for the workround
https://developercommunity.visualstudio.com/t/Private-Unity-messages-incorrectly-marke/10779025
So is it being greyed out the reasons why my "onTriggerEnter" functions dont work
If you've capitalised it like that that'll certainly do it
My collisions still dont work
Then you haven't gone through the all of the links, it's exhaustive as far as I know. If there's an unlisted fix for the issue then I'd love to know
hi , i want check the if light map Bake Type is real time or not , but when i want build the project , it give an error (SOLVED)
`Light[] Spot_Lights = FindObjectsByType<Light>(FindObjectsSortMode.None);
foreach (Light Spot_Light in Spot_Lights)
{
if (Spot_Light != null && Spot_Light.type == UnityEngine.LightType.Spot && Spot_Light.lightmapBakeType == LightmapBakeType.Realtime)
{
Spot_Light.shadows = LightShadows.Soft;
}
}
foreach (Light Spot_Light in Spot_Lights)
{
if (Spot_Light != null && Spot_Light.type == UnityEngine.LightType.Directional && Spot_Light.lightmapBakeType == LightmapBakeType.Realtime)
{
Spot_Light.shadows = LightShadows.Soft;
}
}
`
lightmapBakeType is editor-only. You will have to find another solution to your problem
that my mistake , thank you so much
how do I call a function from another script ? I've been searching around for hours and either I cannot understand what is being said or i can't get it to work
- Get a reference to the script
MyClass myClass = GetComponent<MyClass>(); - Call the required method
myClass.MyMethod();
- Get a reference to the instance you want to call the function on
- Call the function using the reference
Can't answer this due to lack of context and the fact that referencing other scripts has multiple ways
General answer: get the reference of the scrips and call the function. See here how: https://unity.huh.how/references
Choose the best way to reference other variables.
Choose the best way to reference other variables.
Hi! Could you please help me to implement custom factory with Zenject?
I've done "basic" one that resolves context from GameObjectContext and returns facade to me from GameObject context to SceneContext. But I can't implement customization. The idea - I have enemy game context, that have livespan only when game object alive, and I create it via Zenject and provide EnemyEntity as facade for SceneContext(my manager class) to work with it, while other classes/objects of GameContext are hidden.
This code that works for me:
container
.BindFactory<EnemyEntity, EnemyEntity.Factory>()
.FromSubContainerResolve()
.ByNewContextPrefab(enemyPrefab)
.UnderTransform(worldTransform);
public class Factory : PlaceholderFactory<EnemyEntity> {}
But I want create my enemy using instantiate and pass position righ away to it, like I can do using container
container.InstantiatePrefab(enemyPrefab, position, Quaternion.identity, worldTransform)
Unfortunately I can't make it work, while implementing interface, FromSubContainerResolve not working for me, and using ootb I can't get how can I add some data to my object. This is what I've tried.
public class CustomFactory : IFactory<EnemyEntity>
{
///Injections
public EnemyEntity Create()
{
return _container.InstantiatePrefabForComponent<EnemyEntity>(_enemyPrefab, _worldTransform);
}
}
I want to have four types of enemies (different in hp, attack points, color and prefab). I thought I would best use a Scriptable Object for this. But I don't understand how each instance of those can have their own hp and not change that of every else. Is the scriptable object just attached to a normal mono script?
Also I want to have pooling for those enemies. Would it be best to have one pool and assign a prefab each time I release it?
The playfab sdk isnt installing when i click isntall sdk.. I get thrown this error
SOs should just be used for the base states to copy , i use a regular poco to modify the stats
Thanks
don't modify the values on the SOs or all the instances that use that value have the changes. Think static fields
Okay, so I understand that correctly.
Does anyone know if there are rules for .editorconfig to get c# to convert this:
contextMenuItems.Add("Lock", new Dictionary<ContextMenuUIEventType, Action> { { ContextMenuUIEventType.MOUSE_UP, LockItem } });
to this:
contextMenuItems.Add(
"Lock",
new Dictionary<ContextMenuUIEventType, Action> { { ContextMenuUIEventType.MOUSE_UP, LockItem } }
);
when the line length is exceeded?
I can only get it to format like this automatically:
contextMenuItems.Add("Lock",
new Dictionary<ContextMenuUIEventType, Action> { { ContextMenuUIEventType.MOUSE_UP, LockItem } });
Which for me is much harded to read as I always miss the first parameter since it is on the same like as the method call instead of its own line?
hi, i really need help with something. I'm not much of a coder. I'm trying to get a coin sound to increase in pitch per coin up to 5 then reset. (Also reset if theres a big enough gap per coin collected).
You can modify the pitch property of the Audio Source:
https://docs.unity3d.com/ScriptReference/AudioSource-pitch.html
thanks, i'll read through it
hey guys I just have no where in my code where it says that the currentArmor should be 0. And everytime I start the game, that value goes to 0. I am positive that there is no place in any script saying that. any ideas?
are they public ?
[SerializeField] private those so you know for a fact its not being touched anywhere but within that script
make methods / property if you want to interact with it from elsewhere
no they are not
That is my whole class, and I am not using yet any of these getters and setters.. also in the inspector before start the game they also have the value of 1
The only place they are set to zero is here, but I already used debug log and that only happen when the player is touched by an enemy, and it goes to 0 already at the start:
might be a visual bug
Put a log in the setter, then you can check the stack trace where it was set
Chances are you're looking at the inspector of a different object than the one getting changed
There's a very weird thing happening with my Image objects. I have a canvas, which creates some Image elements with a BGLayer component, and based on their Auto Scroll, scrolls them individually by that value (Via their own update method, independent of the parent canvas). I have just switched to canvas instead of sprite renderers to make this cleaner, and before that it worked fine. Layers with 0 auto scroll were still, while ones with anything but 0 (the clouds in this case), slowly moved by that amount every frame.
Now, as seen in the recording, all layers seem to move by the addition of all their individual autoscroll values (As in a 0;0, 0.5;0 and -0.2;0 are all moving at a speed of 0.3;0, the result of adding them all together (???). I have no idea why this might be happening. Can someone please help me figure this out?
-# Files:
Video #1 - Recorded problem
Screenshot #1 - BGLayer Prefab (all values (including the default sprite) are overriden when loading layers from the xml)
BGLayer Class - https://hastebin.com/share/hixecowuco.csharp
BGHolder Class - https://hastebin.com/share/toqoverigi.csharp
Tell me if any other files are needed
-# I repeat, this worked perfectly fine until I switched GameObject with SpriteRenderer to GameObject with Image
I think you might be sharing the same material instance between every image, so you actually adding the offsets
you can try creating a new material instance for each image and then later try applying the offset
althought I must say that using UI for this kind of stuff sounds unusual at least, sprite renderers are probably more adequate
Yeah I think that's it. I just need to find a way to make them scroll individually
Creating a new material dynamically so far breaks it even more
how are you creating the material?
public void Assign() {
imageRenderer = GetComponent<Image>();
rectTransform = GetComponent<RectTransform>();
Material unlitMaterial = new Material(Shader.Find("Unlit/Transparent"));
imageRenderer.material = unlitMaterial;
}
I don't think that's the correct shader, you can probably just do:
Material mat = new Material(imageRenderer.material);
imageRenderer.material = mat;
Hi! If Im doing anything of this in the wrong format tell me - I'm very new to this server, and would be happy to take this message down if needed.
So Im having an issue with my game elements not saving their position whenever I click a button (The "Draw Card" function under Deck Manager). Whenever I do, it will not save the previous positions of my objects, which I want them to save after a player moves them with their mouse. (Ex: player moves the card to the right, clicks draw card, that original card stays to the right while the other card is drawn).
Issue: Cards not saving position when function is called - want to get those positions to save so even if those functions are called, it stays that way
Codes:
CardMovement Script: https://paste.ofcode.org/vhBHVDSJDSY2afEXLVxDCM (This is what all card movements are linked up to, but it does not have the draw card function inside it.)
DeckManager Script:
https://paste.ofcode.org/6HcWvttWCQqnLgf9sB3qid (This is what actually calls for that Draw card function)
(If you do respond, please @ me! I usually miss responses very easily due to working on other problems. Thank you so much!)
how do i create a character that can move (ik this is simple but i just cant)
I tried to create a graph dialog system but I have problems. When I save and then load the graph, even if the nodes appear, the texts inside or the sprites and fonts no longer appear when loaded (before then after load)
did you try debugging already? in which function is the position being reset?
I'm not quite the best at debugging - the main issue i know that occurs is whenever a new card is being drawn. I need to look back at my code, Ill see if I can see if there's anything specific causing it, but whenever I was trying to check it was unclear
This is not a visual script but an editor that I created
you'll need to add Debug.Log statements at every position change and figure out exactly where it's happening, then later it should be easy enough to prevent this change from happening in certain cards
oh sorry, then show us the !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
i need help why do i only have the game scene
like i cant move my screen and i cant change scenes
this is the only thing i can see
how do i do that (im new to unity)
oh thank you
Figured out where it was messing up, but I dont know how to generally fix it.
private void UpdateHandVisuals()
{
int cardCount = cardsInHand.Count;
if (cardCount == 1){
cardsInHand[0].transform.localRotation = Quaternion.Euler(0f, 0f, 0f);
cardsInHand[0].transform.localPosition = new Vector3(0f, 0f, 0f);
return;
}
for (int i=0; i < cardCount; i++){
float rotationAngle = (fanSpread * (i - (cardCount - 1)/2));
cardsInHand[i].transform.localRotation = Quaternion.Euler(0f, 0f, rotationAngle);
float horizontalOffset = (cardSpacing * (i - (cardCount - 1)/2));
float normalizedPosition = (2f * i / (cardCount - 1));
float verticalOffseat = verticalSpacing * (1 - normalizedPosition * normalizedPosition);
//set card position
cardsInHand[i].transform.localPosition = new Vector3(horizontalOffset, verticalOffseat, 0f);
}
}
}
The main thing that I need to do is get that card position to save even when drawing, but to do that it'll effect the new cards drawn position.
Apologizes for how messy that looks, need to figure out how to use the "``cs" command more
I think you just missed a line break after "cs"
huh that's weird
can you add something like a bool wasMoved to the Card object and check it before assigning the new position?
Actually never thought of that! Let me see real quick!
most likely you'll also need to modify how you're counting the cards here
as far as I understood you'll want to keep the fanning effect for the cards that were not moved
Hi I have a question. I'm currently doing inventory by grid layout group. I have grid layout group and next grid layout group in it, if the second grid layout group has so much objects they will start overlap over next grid layout group. Does anyone know how to do better grid layout group?
Or is there better way how to do grid layout?
So I've been doing a 2d Mario-like platformer, and I'm trying to figure out a way to make the player, and all other characters and objects, move in parallel to slopes. I always slip off. Enemies walk away thinking it's a wall, too.
When i type in update nothing comes up and so i cant get things done.
What do you mean nothing comes up? It's literally there.
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
What to do now?
Kindly read the bot message, click a link and follow the steps.
how to move my visual studio community and its installs to another disk?
The easiest way would be to uninstall it, restart your PC, then reinstall it in the location you want.
Alright, been working on troubleshooting the counting card method from before.
Could someone explain to me what these errors mean? It's still giving me the Debug log after where it says the null failed, but it still says the Null failed. What happened?
Issue is on line 46 of CardMovement.cs as the stack trace suggests
It comes directly after instantiating the object it seems
Something is null but you're trying to access it anyway
Thats weird.
Heres the code there, but I dont get what its null?
cardCount = GameObject.Find("DeckManager").GetComponent<DeckManager>().cardCount;
Debug.Log("Found cardInHandCount");
If you wouldnt mind explaining that is. Thank you!
This can error if no "DeckManager" object is found, or if it is but there's no DeckManager script on it
https://unity.huh.how/runtime-exceptions/nullreferenceexception
If you want an explanation and guide
You can get NREs when you dereference (ie. access) with . on a null reference (a variable that is null or something that gives you null)
Like with a.b, if a is null, you get the error
Anything before a .
So, GameObject.Find("DeckManager") or GameObject.Find("DeckManager").GetComponent<DeckManager>()
Ohh! Yeah, it's probably because DeckManager becomes a clone, need to figure out how to exactly correct it
Thank yall for yalls help by the way! It's insanely useful!!!
hey I've got an image with a lot of alpha space in it and it's being picked up as the button press area. Is there a way I can have just inside the arrow be detected as button press?
I tinkered with alphaHitTestMinimumThreshold set to .5f on the image and set read/write on and it made the whole button invisible
This shouldn't affect the visuals of the image.
odd, I wonder why it's doing this. I'm doing an alpha fade on the object after it's instantiated, that's on the image sprite color
Perhaps an issue with your code. Maybe the fading happens faster than you expect?
the alpha fade shouldn't affect the expected collider. My workaround was to just disable raycast hit on everything and add an invisible image for the actual raycast hit that is sized to the arrow
Are we talking about the colliders or the visuals? Colliders don't affect how the image looks like.
Alpha fade does.
You said here that it becomes invisible, which I thought is the issue?
Sorry, I'm talking about how a Unity Button detects a button press. You're supposed to be able to drop in an image and it should use that image as the button. However, my button just has a lot of white space around it, and Unity is getting confused and included the alpha channel in what it detects as a press.
I'd like to exclude the surrounding white space from what Unity detects as a press and only use the inside arrow
Have you tried using an image editor to remove the white area from the image?
Yop,
If you're talking about a 2D button, add a Polygon Collider 2D component, edit it and you should be able to create your own hitbox
btw if you're using a button component, it will take your image as a hitbox, you can't edit it. If you want to edit your button, you have to use a custom collider
if im working on a project with a friend and i check in my changes but they cant see what ive done what is the problem?
Hi! Could someone help me with zenject factories please =)? I've asked few times, not sure if question is unclear or I'm asking in wrong place. I've quite stuck, tried everything and starting to doubt if it's even possible to do what I want 🙂
quick question, for some reason gameobjects in list Borders arent getting destroyed and removed from scene (i instantiated them in some other part of code). Borders.Count give same number as before the loop
here is part of code where i instantiate them
I'm not 100% sure, but I assume it won't remove from list if you won't do it directly.
If you try to call some of objects after removal you will get error I believe.
what's Borders? a list?
the list is going to still have those destroyed gameobjects
yeah Borders is list, border is single game object
they're be invalid, but they won't just drop out of the list
maybe you're looking at ones that aren't in your list 🤷
you can do Borders.Clear() at the end of the deletion method to clear the list
i read that that wont solve problem, it will remove references to them but they will remain on scene
Destroy shouldve removed them from the scene; that's a separate issue
if you want to clear the list, you'll have to use that method afterwards
also i change scene and go back and they still get instantiated (script is part of object which has DontDestroyOnLoad, so they definitelly arent getting removed from the list or are invalid
where's this code in? Start?
sort of but in other parts as well for example when i change color of my borders i call it again and it just adds more borders on top of eachother,
Destroy(obj) doesnt work at all idk how
im not sure how you're linking those 2 statements together 
being reinstantiated is wholly separate from destroying them successfully
what do you mean by "sort of"? is it being called from there or not?
my point is that Borders list keeps all members for some reason even after destroying and they stay on scene
its called on request
that's because that's how lists work
objects being in the list and objects being in the scene are separate concepts
okay but my idea was to store each instantiated object in one list and delete them all before instantiating updated version of borders if you understand me
idk how to keep track of all instantiated objects otherwise
sure, but you'll have to clear the list after deleting them
you have 2 separate issues right now, you're conflating them
is Borders getting reassigned anywhere?
no. give me as econd to check something
actually, probably more useful: does Border.Count align with the amount of borders you see in the scene?
yes bro
try logging obj.name, see if those line up with what you're expecting to be destroyed
good call
btw even .Clear didnt help 
its like i am losing reference the the object i am trying to destroy
maybe if i put it as parent of some object and destroy all childrens of it

sure, that could work
will try tmrw i am dead tired 
You need to remove them from the list first, then destroy them. You can't remove a reference from the list if it's already destroyed . . .
im using a distant joint as a rope swing however its causing gravity to not affect my player at all and i dont know why. like instead of swing it just very slowly move to the bottom of the joint
ok its affecting it now slightly
if i swing the player up it will fall down but then as soon as the distance joint2d constrains it from falling further all that vertical movement is just killed instead of converting into a swing
the thing the reference points to is destroyed, the reference itself isn't
like i dont get why its killing its speed for no reason
you're probably setting the velocity or position somewhere, and not letting momentum/gravity handle that
ill check but i dont think so
can't really help with code when we don't see the code...
public void SetInMove(float newMove)
{
if ((newMove > 0 && m_isCrouchedNearLedgeRight) || (newMove < 0 && m_isCrouchedNearLedgeLeft))
{
// Prevent movement if crouched and near a ledge
return;
}
m_InMove = newMove;
}```
thats what im using for movement
apart from that im not sure
oh wait hang on
{
while (m_RB.linearVelocityY > m_apexTrigger)
{
yield return null;
}
m_inApex = true;
m_RB.gravityScale = m_RB.gravityScale * m_apexGravityScale;
if (m_currentScene > 2 || m_hasCompletedTutorial)
{
m_MoveSpeed = m_MoveSpeed * m_apexSpeedBoost;
}
while (m_RB.linearVelocityY > -m_apexTrigger)
{
yield return null;
}
m_inApex = false;
if (m_currentScene > 2 || m_hasCompletedTutorial)
{
m_MoveSpeed = m_MoveSpeed / m_apexSpeedBoost;
}
m_RB.gravityScale = m_normalGravityScale;
}```
maybe my jump apex handler is affecting it
None of this code or the other code you posted actually handles movement
it's only setting the m_MoveSpeed variable
oh shoot u right
ah
i think i see the issue
{
m_RB.linearVelocityX = m_MoveSpeed * m_InMove;
}```
when im not pressing keys
me velocity x
will always be 0
yep
so disable fixed update while in rope swing?
well you can't disable FixedUpdate without disabling the script. But you can put this particular code inside an if statement
yeah thats what i meant
UnityEngine.InputSystem.LowLevel.NativeInputRuntime/<>c__DisplayClass7_0:<set_onUpdate>b__0 (UnityEngineInternal.Input.NativeInputUpdateType,UnityEngineInternal.Input.NativeInputEventBuffer*)
UnityEngineInternal.Input.NativeInputSystem:NotifyUpdate (UnityEngineInternal.Input.NativeInputUpdateType,intptr)```
why am i getting this error
i subscribe to an action on the player
but when the scene is unloaded
and i press the button which invokes the action
i get that
ok well its randomly started working
wait no
some times it works some times it gives me the error
weird
I added an Animation Event. I am unsure how to tell it to look for a function like before? Is there a new way of doing this?
if scriptable object Weapon inherits from Item how do I get Weapon weapon out of List<Item> items?
I am unsure if you are talking to me. But if you are heres a image of what I am talking about just in case.
I did end up figuring it out. Having () broke it.
You can try casting the item into a weapon object. But to be fair, if you need the specific type, you might be doing something wrong.
foreach(Item in items) {
if(item is Weapon weapon){
//found a weapon
tip: use single backticks to get inline code
So each Item has attributes like a name and a bunch of textures, but then the Weapon has damage, cooldown, projectile attributes etc. Is this bad?
that's not bad, but the part that might be is storing all the items together and having to find Weapons specifically.
if items really are stored together, then it shouldn't really matter if one is a weapon or not
if weapons are stored separately, then they should be in code, too
It's not bad, but why do you need to make a distinction at that point? Ideally, you should make use of polymorphism to avoid casting. That being said, it might be justified in some cases.
this may be a case of https://xyproblem.info, so you might want to elaborate on what you're trying to achieve here so we can give proper advice specific to your situation
for example, if you're making a sorting system for an inventory, it would definitely make sense to have this kind of check
I have it set up so that there is an enum that is used as an index for the List<Item> inventory, making 0 - 9 equipment slots and the rest the general inventory of an entity. Once an item passes a check it can be equipped into one of those slots or used as a consumable, and at that point the polymorphism matters. It made a lot of the code I did way more simple and with fewer lines, but its mostly so I don't have to look at a bunch of unused attributes when I make a scriptable object.
so a potion doesnt have a projectile type or an armor class.
couldn't you just have an enum ItemType for Consumable, Equippable, Weapon etc and just check that instead of checking what class it is?
that would make it much easier to make new item classes, as you'd just have to mark the item as that type
you might not always be able to extend existing classes even for items of the same type
for example, Weapon right now seems to be a firearm, but a melee weapon wouldn't have projectile info, so you wouldn't be able to extend it
of course you could use classes to specify that type, ie make Weapon only have like, cooldown, but weapons as a whole are kinda too diverse to have anything else, and that isn't really meaningful to make a whole class for
(although, cooldown would probably be something items have in general...)
does anyone have a super efficient awesome way for playing png sequences un unity, with transparencies?
im currently preloading all of the images and then iterating through them on a rawimage.texture
private void FixedUpdate()
{
if (isPlayingSequence && overlayFrames.Count > 0)
{
float currentTime = Time.time;
if (currentTime >= nextFrameTime)
{
overlayRawImage.texture = overlayFrames[currentFrameIndex];
nextFrameTime = currentTime + frameInterval;
// Move to the next frame
currentFrameIndex++;
if(currentFrameIndex == 2)
{
SetRawImageAlpha(1f); // Make the overlay visible
}
// Check if the sequence is complete
if (currentFrameIndex >= overlayFrames.Count)
{
StopSequence(); // Stop and clean up
}
}
}
}
public IEnumerator LoadSequence(string imagePathPrefix)
{
overlayFrames.Clear();
currentFrameIndex = 0;
int frameIndex = 0; // Starting frame index
Texture2D frame;
Debug.Log($"Loading overlay frames from {imagePathPrefix}{frameIndex:D3}...");
while ((frame = Resources.Load<Texture2D>($"{imagePathPrefix}{frameIndex:D3}")) != null)
{
overlayFrames.Add(frame);
frameIndex++;
}
if (overlayFrames.Count > 0)
{
Debug.Log($"Loaded {overlayFrames.Count} frames for sequence {imagePathPrefix}.");
}
else
{
Debug.LogError("No overlay frames found in Resources.");
}
yield return null;
}
public void PlaySequence()
{
if (overlayFrames.Count > 0)
{
isPlayingSequence = true;
currentFrameIndex = 0;
nextFrameTime = Time.time + frameInterval;
EnableOverlay();
}
else
{
Debug.LogError("Cannot play sequence. No frames loaded.");
}
}
im looking into going with an atlas and a shader to do it instead currently
the assets are too big to stitch into a single sprite sheet
How about an animation?
im currently trying that actually. just converted the sequence to sprites and dragged them in
I have looked it over thousends of times but it doesnt work for some reaons:
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float jumpForce = 5f; // Hoe hoog de speler omhoog gaat
public float moveSpeed = 5f; // Hoe snel de speler naar rechts gaat
private Rigidbody2D rb;
void Start()
{
// De Rigidbody2D van de speler ophalen
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
// Check of op de spatiebalk is gedrukt
if (Input.GetButtonDown("Jump"))
{
// De huidige snelheid resetten zodat de speler gelijk omhoog gaat
rb.velocity = Vector2.zero;
// Kracht naar boven toevoegen
rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
}
// Automatisch naar rechts bewegen
rb.velocity = new Vector2(moveSpeed, rb.velocity.y);
}
}
What's the error said
You're immediately overwriting the velocity on the last line which undoes everything that the jump code does.
The code looks like it's written by ChatGPT. Look up a basic movement tutorial, there are a lot of them
Hey, i'm following a tutorial on state machines, and i've just implemented it, but i can't really call a SwitchState method from a button or anything of the sort
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
what am i doing wrong here?
(Oh yeah i forgot i made the googoogaagaa method just to see if i could actually call anything from this one)
You can only assign methods with parameters that unity supports to a button on click event in the inspector.
Alright
That makes sense
I don't know if that'd be considered a hacky solution, but what if i implemented an enum with all my states and switched the state machine through that?
That's fine.
A better solution would be to specify the parameter in your custom script attached to the same object. The button would call a parameter less method on that script and the script would use it's parameters for invoking whatever API you need.
I'm having some trouble following, would that just boil down to building a bunc of SwitchToXState() methods?
I think it's because "Jump" is not a key. Replace it with this: if (Input.GetKeyDown(KeyCode.Space)) PS: Volgende keer je code even formatten 😉
No. It boils out to one method and a serialized field(your parameter) of your desired choice.
for a start, your Visual Studio isn't configured... do that first. See the bot msg below
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
'wrong' tells us nothing. You will need to provide actual details
We can see that
and type in full sentences
I've spotted 1 error .. which Unity will tell you what it is and where it is. But, configure your Visual Studio before continuing
Once you've sorted your VS out, IT will tell you what and where the error is
ok, that's irrelevant
I can SEE it is not configured
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
READ the guide linked twice now.
a beginner at reading?
Here, I'll even give you the correct link so you don't have to think above the two provided in the bot msg
https://learn.microsoft.com/en-us/visualstudio/gamedev/unity/get-started/getting-started-with-visual-studio-tools-for-unity?pivots=windows#configure-unity-to-use-visual-studio
don't yet know what?
All you have to do is click the link, read, and follow the guide. ¯_(ツ)_/¯
Yep.
Clicking the link takes you directly to a specific section on that page.
what do you think this says?
READ 😄
Being "new" to Unity isn't relevant. You just have to read a guide and follow it..
then probably game dev is not for you
||Don't listen, read||
unity doesn't use c++
there are more steps to follow, do them all
Unity requires the C++ VS module to be able to build IL2CPP
if you don't properly configure your ide, it won't be effective as an actual ide, it'll just be a text editor
a properly configured ide highlights errors and provides autocomplete
you scrolled up, instead of starting from where the link took you and scrolling down
it'll make your experience much better
40 mins after first being told about them 😄
I would love to hear what you have actually done in terms of steps
If you're just going to talk nonsense for an hour, please stop posting.
You have been given help for the past two hours and all you have been able to do is respond with lazy, uninformative answers
Either give clear answers that people can actually use, or don't bother asking for help
I want you to properly explain what you did in regards to configuring your editor. Explain the steps and show that you have done them
If you truly followed all the steps, then it should all match
Then show it
I don't see the point with this back and forth bickering, either post your process so people can spot the problem or nobody is going to help you
!ban 349901428912816139 Ignorant stubborn child
highvoltage2011 was banned.
was going to mute them before insults...
So I recently figured that a parent having a Rigidbody2D soaking up all OnTriggerEnter2D and OnCollisionEnter2D events onto itself
Scripts on child GameObjects having colliders seem to ignore those iirc
That's pretty annoying because I seem to be having to make a huge if-else(or rather switch) thingie on the main parent object to figure out what exactly have collided with which exact subcollider, because I want different responses for different colliders
What do I better do?
Also it seems like changing a Layer of those child GameObjects having colliders doing nothing in terms of collisions, it's just changing their rendering layer, I am having to tune their colliders Layer overrides because they seem to obey the parent layer
this is so confusing, I feel like it was poorly designed
well it will be called on the gameobject with the rb
the biggest issue seems to be is about trigger entering
because it only returns a second collider, but not the receiver
anyway it's not what bothering me but the fact I am having to do a big if else thingie so the script figure out what are we colliding with
I guess there is no workaround there
so you just want to know on which child object the collision happened or
yeah that's... still same amount if switches really
I tuned my layers in a way that there are no unwanted collisions
well, maybe it's better optimization wise to have one big if else script instead of bunch of tiny ones on each subcollider...
How can we understand anything from this ambiguous screenshot and description
I might assume you want to freeze rotation on the player rigidbody if he is using that component even
- rotation code is broken
- animations are broken
- rig is missing/broken
- pivot is broken
I can't figure out how to fix this."
Have you wrote your code of moving yourself or at least do you understand how it works?
i undestanding how works the code
so what do you use to move the character?
float forward = Input.GetAxis("Vertical");
float right = Input.GetAxis("Horizontal");
that does not move anything
this is all code
point is, as you could not answer the question, you do not understand your own code
Well, I showed how I moved horizontally and vertically
no you did not
if you are referring to the movement animation it is written below in the code I created a variable in the animator which I set as in , I created the transition and when the character is in idle state it takes the value 1 i.e. true and vice versa
Do you want me to explain everything with direction and speed?
I would rather want you to explain why did you thought that spinning a character getting mouse movement is a good idea
that's kinda... insane
You should probably watch a tutorial or two how to make player movements using a character controller or a rigidbody
I don't feel like you have a grasp on what are you doing given your responses and the code itself
You should completely rewrite that
Btw you can make animator boolean params, you don't have to use 0 or 1 integer
Hey, I'm a newbie on dev and was thinking about how to approach some topics using logic.
For example, I wanted to make a pixel filter with outlines. How do I even start such task? Do I go learn all I can about how does a shader work and start one from the ground? There are some guides on it but the ones that do explain what I wanted to hear already presume I have a built shader.
Logical thing would be to have someone else solve it by using something like the very capable All-In-One Sprite shader pack on the asset store so you can focus on making your game.
I don't have money for that :(
Asking because I am clueless, what is the "pixel filter with outlines"?
The shader making stuff pixelated and having an outline, I figured
Easy, Good, Free. Pick two.
time to go learn shader magic 
I hate shaders... I lack comprehensive knowledge about how to make them, but given what I know I would advice to not trying to make ones yourself
unless you really really have to
Yes, learn the dark arts.
But every cool 2D game I see is made by a shading wizard with lots of cool baked VFX
Literally
I dunno what are you talking about, I had an impression that it's all about sprite graphics
why advise someone not to do smth because you hate it and lack the knowledge to do so?
I tried and it didn't work out well 🤷♂️
That's definitely not one of the things you should do when you are starting out
Hi. how to change gravity from script without using rigidbody
If you aren't using a rigid body how are you handling gravity?
do you mean change the constant gravity variable or what
if you're not using a rigidbody then how is the object affected by gravity?
so i cant? without this
Well, Gravity as a Unity-defined concept only applies to Rigidbodies.
If you aren't using them, you'd need to write your own gravity
my player change gravity after like 0.5sec when he is on block.
and character controller, kinda
No, CharacterController has no gravity built in
Okay, and what are you doing that applies gravity
it applies gravity on SimpleMove to it
Ah, I forgot about SimpleMove
i try use gravity after click button using constant force or gravity in inspector
with script
If you're using SimpleMove and want to change the gravity, the solution is don't use SimpleMove
oh okey
wait, do you use a Character Controller?
yes and no
._.
If you won't actually say what you are currently doing then no one can help you fix anything
i was try script with this and without this
"character controler"
Character Controller is a component you put on your GameObject, player I guess
but it work not like i want
it's an alternative to a rigidbody
this is it?
or somethink like this?
i found this
you guys mean with (CharacterController)
wow, this is ancient. that's unity script . . .
This isn't C#
oh
this thing?
I made my first FPS game using it but it's kinda lame, no physics interactions whatsoever
well, no realistic ones
no built in inertia, and you push rigidbodies like you have infinite mass
wdym
or i say wrong
what?
using (for example) animation on button in inspector you cant move everyblock
from hierarchy
sorry for bad english
yeah I figured there should be some language misunderstanding
xd
I still don't understand what do you want to say however ><
i use for button space animation move
but if i move somethink in inspector
i move only one block
character controler this green block (these lines) when u have box colider
i need move all
(player)
and im stuck so ;/ i ask here how to fix this
do you say "block" wanting to say a "collider"?
for move like i want
Usually, if you have a child GameObjects in the hierarchy
when you move parent, all childs move along
the only exception I know is when a child having a "Rigidbody" component
this case if you need it you have to set it to be kinematic
in animation same
and if that's a character controller, well, you are not supposed to have child character controllers
it should be on the main parent object
wait kinematic?
i check wait
where it is? in inspector or i need in script
In inspector
or dynamic
Body Type
like, upper parameter
How your character hierarchy looks like anyway?
I mean the player
because I have feelings like you don't need several rigidbodies
it work same with kinematic
;/
i have just rightbody with kinematic on
but work same
can you formulate
what do you want to do
what do you do
and what is going wrong
wait i need ask
what if there is an option such that it adds +1 all the time in transform “y” and when I change the gravitations it adds -1 it will fix it
in c# is option like this?
or no
it's not about C# it's about Unity and yeah you can just
ignore all that rigidbody charactercontroller stuff and make gravity manually
assuming you don't need to interact with anything
using colliders
i will try
i have copy of geometry dash but difrent and i need change gravity player
(3d gd game)
i have some plans
and i need it
well there are indeed colliders and you have to use a rigidbody
u give me idea
however it would be easier to uncheck rigidbody using a gravity
and emulate it yourself
{
if (body.velocity.y >= 0)
{
body.velocity -= new Vector2(0, jumpConfig.upGravity * Time.fixedDeltaTime);
}
else
{
body.velocity -= new Vector2(0, jumpConfig.downGravity * Time.fixedDeltaTime);
}
}```
look, that's my method in the FixedUpdate loop for a sloppy platformer I made
you should put something like that into FixedUpdate
basically multipication of deltatime passed on your wanted acceleration summed up with current rigidbody velocity
i will try this
yeah just not copy the code but copy the principle
wait... geometry dash
straight lines.. I am not sure it even uses acceleration
maybe it's just gives constant velocity up/down
i try now change transform "y" in animation after click and it work but my player cant move
what do you mean by an animation
I am still not understanding what is going on your end well and gtg, sorry
YES I DID IT
i add game object
and after this block to this
move player to block and change gravity on animation to gameobject
thanks for help ❤️
so i am trying to make a build sistem based on a database here s the thing:
sorry
i try to make the transparent prefab to follow the mouse
but i just can t think of a reliable way
(my code is build from 3 diffrent tutorials if you want i put the links in)
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class InputManager : MonoBehaviour
{
[SerializeField]
private Camera sceneCamera;
private Vector3 lastPosition;
[SerializeField]
public RaycastHit hit;
[SerializeField]
private LayerMask placementLayermask;
public event Action OnClicked, OnExit;
private void Update()
{
if(Input.GetMouseButtonDown(0))
OnClicked?.Invoke();
if(Input.GetKeyDown(KeyCode.Escape))
OnExit?.Invoke();
}
public bool IsPointerOverUI()
=> EventSystem.current.IsPointerOverGameObject();
public Vector3 SelectMapPosition()
{
Vector3 mousePos =Input.mousePosition;
mousePos.z=sceneCamera.nearClipPlane;
Ray ray=sceneCamera.ScreenPointToRay(mousePos);
if(Physics.Raycast(ray,out hit,100,placementLayermask))
{
lastPosition =hit.point;
}
return lastPosition;
}
}
i understand that i need to somehow put a refference in the update function
!code, Do not use screenshots unless asked. Do not post large blocks of code directly into the chat
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
i saw that too late sorry i used the firs link to re-send this
so i give you the url in chat? sorry i am new
Use this (```)
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class PlaceingObj : MonoBehaviour
{
[SerializeField]
private InputManager InputManager;
[SerializeField]
private DatabaseSO database;
private int selectedObjectIndex=-1;
void Start()
{
StopPlacement();
}
public void StartPlacement(int ID)
{
StopPlacement();
selectedObjectIndex =database.objectsData.FindIndex(data => data.ID==ID);
InputManager.OnClicked += PlaceStructure;
InputManager.OnExit += StopPlacement;
}
private void TransparetFlow()
{
GameObject newTransparentObject = Instantiate(database.objectsData[selectedObjectIndex].TransparentPrefab);
newTransparentObject.transform.position=InputManager.SelectMapPosition();
}
private void PlaceStructure()
{
GameObject newObject = Instantiate(database.objectsData[selectedObjectIndex].Prefab);
newObject.transform.position=InputManager.SelectMapPosition();
}
private void StopPlacement()
{
selectedObjectIndex =-1;
InputManager.OnClicked -= PlaceStructure;
InputManager.OnExit -= StopPlacement;
}
// Update is called once per frame
void Update()
{
InputManager.OnClicked += TransparetFlow;
if(selectedObjectIndex <0)
return;
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class InputManager : MonoBehaviour
{
[SerializeField]
private Camera sceneCamera;
private Vector3 lastPosition;
[SerializeField]
public RaycastHit hit;
[SerializeField]
private LayerMask placementLayermask;
public event Action OnClicked, OnExit;
private void Update()
{
if(Input.GetMouseButtonDown(0))
OnClicked?.Invoke();
if(Input.GetKeyDown(KeyCode.Escape))
OnExit?.Invoke();
}
public bool IsPointerOverUI()
=> EventSystem.current.IsPointerOverGameObject();
public Vector3 SelectMapPosition()
{
Vector3 mousePos =Input.mousePosition;
mousePos.z=sceneCamera.nearClipPlane;
Ray ray=sceneCamera.ScreenPointToRay(mousePos);
if(Physics.Raycast(ray,out hit,100,placementLayermask))
{
lastPosition =hit.point;
}
return lastPosition;
}
}
guys this code doesn't work and IDK why
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu]
public class DatabaseSO : ScriptableObject
{
public List<ObjectData> objectsData;
}
[Serializable]
public class ObjectData
{
[field: SerializeField]
public string Name { get; private set; }
[field: SerializeField]
public int ID { get; private set; }
[field: SerializeField]
public Vector2Int Size { get; private set; } = Vector2Int.one;
[field: SerializeField]
public GameObject Prefab { get; private set; }
[field: SerializeField]
public GameObject TransparentPrefab { get; private set; }
}
i want to move the transparent prefab along with the position of the mouse
i understand that i need to put a reference in the update
but i get this error
You're trying to get an index from a collection that is either negative, or larger than the collection's size
wait wait i modified sth
What doesn't work about it
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class PlaceingObj : MonoBehaviour
{
[SerializeField]
private InputManager InputManager;
private transparentMovement transparentMovement;
[SerializeField]
private DatabaseSO database;
private int selectedObjectIndex=-1;
void Start()
{
StopPlacement();
}
public void StartPlacement(int ID)
{
StopPlacement();
selectedObjectIndex =database.objectsData.FindIndex(data => data.ID==ID);
InputManager.OnClicked += PlaceStructure;
InputManager.OnClicked += FixedUpdate;
InputManager.OnExit += StopPlacement;
}
private void PlaceStructure()
{
GameObject newObject = Instantiate(database.objectsData[selectedObjectIndex].Prefab);
newObject.transform.position=InputManager.SelectMapPosition();
}
void FixedUpdate()
{
database.objectsData[selectedObjectIndex].TransparentPrefab.transform.position=InputManager.SelectMapPosition();
}
private void StopPlacement()
{
selectedObjectIndex =-1;
InputManager.OnClicked -= PlaceStructure;
InputManager.OnExit -= StopPlacement;
}
// Update is called once per frame
void Update()
{
if(selectedObjectIndex <0)
return;
}
}
what is it that i try to acces and doesn t have a valid index?
Not sure, what does the error say
What line?
i don t know how to debug otherwise than hitting play in unity
Do you know how to click on something and read it
which is...
oh wait
You will notice that since you did not post the !code to a bin site, I have no line numbers
📃 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.
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class PlaceingObj : MonoBehaviour
{
[SerializeField]
private InputManager InputManager;
private transparentMovement transparentMovement;
[SerializeField]
private DatabaseSO database;
private int selectedObjectIndex=-1;
void Start()
{
StopPlacement();
}
public void StartPlacement(int ID)
{
StopPlacement();
selectedObjectIndex =database.objectsData.FindIndex(data => data.ID==ID);
InputManager.OnClicked += PlaceStructure;
InputManager.OnClicked += FixedUpdate;
InputManager.OnExit += StopPlacement;
}
private void PlaceStructure()
{
GameObject newObject = Instantiate(database.objectsData[selectedObjectIndex].Prefab);
newObject.transform.position=InputManager.SelectMapPosition();
}
void FixedUpdate()
{
//38 database.objectsData[selectedObjectIndex].TransparentPrefab.transform.position=InputManager.SelectMapPosition();
}
private void StopPlacement()
{
selectedObjectIndex =-1;
InputManager.OnClicked -= PlaceStructure;
InputManager.OnExit -= StopPlacement;
}
// Update is called once per frame
void Update()
{
if(selectedObjectIndex <0)
return;
}
}
didn t notice there are no line numbers
and yet you posted it, again, with no line numbers
Use a bin site like the bot says
i commented the line number 😦 i don t understand how to use that site
but i will try
Paste code, get link, send link
Don't use the first link as it's broken
a powerful website for storing and sharing text and code snippets. completely free and open source.
void Start()
{
Debug.Log($"This script is attached to: {gameObject.name}");
Debug.Log(privateFloat);
Debug.Log($"privateFloat: {privateFloat}");
}``` `Debug.Log` simplest way to debug, you leave yourself messages and log script values, basically leaving little breadcrumbs to see what does and what doesn't run, when and how u expect them to..
There is nothing in FixedUpdate to protect against invalid indices
There is a partial check in Update that does absolutely nothing
what are invalid indices
ok now i understand the error but i still don t know how to do my thing
https://paste.myst.rs/ypsrjxul this is thefull code
a powerful website for storing and sharing text and code snippets. completely free and open source.
hey is "private" used so people cant hack your game through the inspector?
this is what i want to do
no...?
no, it has nothing to do with security
it's just a way of signaling that you don't expect that value to be modified from outside of the class
alright thanks for the help
Hi! I have an idea to make a cutting tool that can cut through walls, who knows the best method for that? Should I use some unity asset already made, or should i go and code this myself? Here's a video for concept..
Yes.. I know the way im doing this is incredibly stupid but it was just a test idea.
Also totally not copyrighted assets
I dont know how or of any slicers that could follow a custom path
And not just cut in half
@stuck monolith You've already been directed before to use !collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
I do not like how I you have that
Well, when you create your own Unity discord with 60,000 members you can do it differently
is there a way to check if a button is being rendered or not?
I see it has a canvas renderer, but not a regular renderer on it...and CanvasRenderer does not inherit from Renderer for some stupid reason.
anyone have an idea on how to make the ball less floaty? i tried increasing mass but it didn't help :/
Gravity famously affects all objects the same regardless of their mass
It looks like the board is about 30 meters tall. That's how it would look like if a 1-meter ball goes up and down 30 meters. Make the whole thing smaller and it'll act more like a realistically sized pinball table would
lol
i scaled it down to like 0.2
Does anyone know why my visual studio refuses to open my script? I can't open it via the component, the asset png, force opening it from file explorer, i've checked and double checked that its in my preferred external tools, regenerated my project files, deleted and remade my game object, and can't seem to open the script
I'm making a 3d game but I can't figure out how to constrain the camera so I can't do vertical 360s. I have tried Mathf.Clamp in every way I can imagine.
