#💻┃code-beginner
1 messages · Page 59 of 1
Most likely the issue is unrelated to this code. Probably you're missing EventSystem component (which is necessary for all UIs on scene to work) or some other object is in front of your button (which blocks raycasts and access to the button).
It has nothing to do with Visual Scripting
That's what I originally thought the problem was -- that it wasn't partially masking the text
but I'm a little unclear on what the issue is..
Thank you!
thanks
I never actually knew about that until recently
I just did it manually with an OverlapSphere
You likely still want an ovelap so you know which objects to call AddExplosionForce on
true; this just does a little extra math for you
oh my god you are still here
i remember your name from 3 years ago
No one else wants me around 😭
have you made any games

how come ;(
They keep adding new stuff to Runescape
hahahahaha
yea 😄
people say making games ruins the magic of playing them
i saw they messed with the wilderness again
now I cannot play a single player game ever again
RS3 maybe but OSRS is still fine
Just added new bosses to it recently actually
sometimes I have a problem in Pokemon Go and realize I might know why it happened
i should go play OSRS. I did RS3 for a few months and then burned out really hard
unfortunately i am no longer a small child and have trouble playing games non-efficiently
i cannot see a cool indie game without the burning desire of making it which wont go away until i try
For me it's the opposite, i always played games trying to break apart how things work. I cant imagine many scenarios where someone learns how an effect is made, then doesnt wanna play a whole game because they know fire is now just a particle systen and not real fire in their monitor
no no its not that at all
for me its just that I wasnt ever a single player game type of guy
and even though I have a big passion for seeing how cool alot of indie games are I still dont enjoy any single player game except like assassins creed but even that I cant come to enjoy anymorer
im still very intrigued by all types of games though and rather watch someone play them than play them myself for some reason
I am trying to make a spawn manager script that randomly picks from one of three prefab models, where should I start?
Make a list of game objects. Pick a random number that's less than the length of the list.
If you have a more specific component on all of the prefabs, you should make a list of those instead
so, for example..
[SerializeField] List<Bullet> bullets;
void Start() {
int index = Random.Range(0, bullets.Count);
Bullet newBullet = Instantiate(bullets[index]);
}
create a list of prefabs, then randomly select one of them?
||```cs
public List<GameObject> listOfPrefabs;
//in some method
var randomPrefab = listOfPrefabs[Random.Range(0, listOfPrefabs.Count())]
this would work if all of my prefabs had a Bullet on them
Yeah I have created around 4 prefabs made in a prefab folder for the project and need one of them to be spawned in randomly in a random direction
So I trying to understand how to put that in a script
Break the problem down (simplify it). Create the list and get the random selection of the target first.
So I guess my question for that would be how do I get the script to have the prefabs as targets
Like how to I have them as objects in the script
It's a bit hard to help when we don't understand what part you are stuck on.
is it selecting a prefab, spawning a prefab, moving it in a random direction, creating a random number?
Create a list?
simex's answer will let you do that.
A List<GameObject> will show up in the inspector.
You can drag the prefabs into it.
Are you simply stuck on implementation of code?
If so, maybe check out the tutorials pinned on this channel 
A little bit yeah
Ok I think I am getting it. So the list is open-ended but in Unity you can drag the objects you want in the list to the script?
If I wanted them spawned ever 0.5 seconds is that in the Update method?
The easiest way would be to use a coroutine.
Are you finished with the referencing of objects first?
I'd break this down in to simple steps, all off these should be simple to google. or maybe even ask here
- Learn how to spawn a prefab.
- Learn how to spawn a list of prefabs.
- Learn how to spawn just one item from a list of prefabs.
- Learn how to select a random element from a list, then spawn that.
- Learn how to move an object that has been spawn by code.
- Learn how to create a random movement.
But yes, get that done first.
Worry about spawning many objects after you can spawn one object
This is what I have:
public class SpawnManagerA : MonoBehaviour {
public List<GameObject> listofPrefabs;
// Start is called before the first frame update
void Start() {
}
// Update is called once per frame
void Update() {
var randomPrefab = listOfPrefabs[Random.Range(0, listOfPrefabs.Count())]
}
}
Looks good.
This will get a random prefab every frame.
It won't do anything with it, of course.
OK Thanks
it's just listOfPrefabs.Count not listOfPrefabs.Count()
So I am trying to add the script to an empty game object but I keep getting this error:
Can't add script component 'SpawnManagerA' because the script class cannot be found. Make sure that there are no compile errors and that the file name and class name match.
well, have you checked for the problems the message is talking about?
you must have zero errors in the console
including errors for other scripts
Make sure that there are no compile errors and that the file name and class name match
The names match
and the other thing?
I have no errors so far, at least that is what Visual Studio is saying
What does unity say
I dont know how to compile it on unity tbh
Unity will try to compile your code whenever it sees changes.
If it has any problems, it will put errors in the console.
Look at the console.
It saying nothing
Screenshot the entire console and show us.
Show the script for SpawnManagerA
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnManagerA : MonoBehaviour {
public List<GameObject> listofPrefabs;
public char 'c';
// Start is called before the first frame update
void Start() {
}
// Update is called once per frame
void Update() {
var randomPrefab = listOfPrefabs[Random.Range(0, listOfPrefabs.Count)]
}
}
First off, !code for how to format it.
Second, if this is exactly copy pasted from your code then I guarantee you have an error send a screenshot of your unity console
📃 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.
Ah ok I didnt know how to format that sorry
That char is an issue
that line is malformed, yes
I might be a bit off base here, but it seems to me like you'd get a lot out of a quick "how to unity" tutorial. something like this: https://www.youtube.com/watch?v=j48LtUkZRjU&list=PLPV2KyIb3jR5QFsefuO2RlAgWEz6EvVi6
it's just that, yes, people here could just give you the copy / paste code that does what you want. but it's kind of like asking:
what's the answer to ∫(2x^2 + 3x + 1) dx
and you get: answer is (2/3)x^3 + (3/2)x^2 + x + C
it doesn't really help anything, if you don't understand the question, or the answer 😅 because you don't learn anything that way
Want to make a video game but don't know where to start? This video should help point you in the right direction!
♥ Support my videos on Patreon: http://patreon.com/brackeys/
····················································································
This video is the first in a mini-series on making your first game.
···············...
Make sure you ide is properly configured. 'c' is not valid.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnManagerA : MonoBehaviour {
public List<GameObject> listofPrefabs;
// Start is called before the first frame update
void Start() {
}
// Update is called once per frame
void Update() {
var randomPrefab = listOfPrefabs[Random.Range(0, listOfPrefabs.Count)]
}
}
Not really off base at all
This will still not compile. Please show us your console.
Okay, so, that got rid of the problem line. Does it work now?
I recommend a c# tutorial like:
https://www.w3schools.com/cs/index.php
Personally I found a pure c# tutorial more helpful than a unity-specific one
There are also other resources in the pins of this channel
They removed the char line. What else is the issue?
This is the consol. It has nothing at all because I dont have the spawn manager as a component to anything yet
Missing semicolon.
You have errors hidden.
It would show even without it attached
Click that button to show them.
Ah, nice catch
Semicolons
I completely glossed over the char line, mentally autocorrecting it into char x = 'c';
🫠
Sorry about that
Can someone help me, I’m trying to make a mobile runner game and I can’t find the template for it on my editor
You need the older editor (i think 2021).
They were removed from at least 2022
You should be able to find Unity official templates on the asset store as well.
I think this is the main problem but IDK what that means
Duplicate script
Oh I was using 2022 thanks
#💻┃code-beginner message
This too
Is it conflicting with a move forward script then? it has a start and update method in it as well
Ok thanks
Is the name of the class the same? That is the issue
You can have as many starts and updates as you want (theoretically)
no, it's a duplicate or the SpawnManagerA class
if you are using vs code and you moved or renamed the file then hit save in vs code again then you just recreated the same file that you originally moved/renamed
You definitely have a duplicate somewhere. That is what the error is telling you
So I have to go digging then I guess
it's a very easy mistake to make
i do it occasionally
Just search for project for "SpawnManagerA" and you'll find the duplicate.
ctrl-shift-F in VSCode, at least.
I'm just gonna refer back to this, because at this pace I don't think you're gonna run out of questions anytime soon
i honestly prefer visual studio's method of handling changes to files. it tells you the file you were editing no longer exists and basically forces you to open it again. very handy to prevent accidentally duplicating something when you've moved or renamed it inside of unity/filesystem instead of using the refactoring tools in VS
you can use the search tools in whatever IDE you are using to find it. you should be able to search the entire project with that
Ok I fixed the dupilicate problem. Now it says that prefabList does not exist in current context
You had listOfPrefabs
Not prefabList
well, yes, you didn't name the field prefabList
Sorry was just typing that not that it was the correct name
the error does say listOfPrefabs my bad
Trying to use it outside of SpawnManagerA without a proper reference?
Show the code where the error is
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnManagerA : MonoBehaviour {
public List<GameObject> listofPrefabs;
// Start is called before the first frame update
void Start() {
}
// Update is called once per frame
void Update() {
var randomPrefab = listOfPrefabs[Random.Range(0, listOfPrefabs.Count)];
}
}
i am also going to point you back to this.
You should use things that exist instead of things that do not
first, make sure that your !IDE is configured
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Can’t find it in asset store
Sorry I have three classes this year using java, c#, and c and I am constantly having to change it. C# is completely new to me but its not too bad
Java and C also require you to spell things correctly
Configuration should switch when you open the project file afaik, so you'd only have to do it once per language (per device)
At least that's how it is for me when I jump between languages
Is Computer science a major I should go for in college cause I heard it’s a job that there is gonna be too much coders for in the next 6 years
What did I misspell?
this is not a code question and not a unity question
configure your IDE and it will show you 😉
every single error you have is caused by a typo or incomplete name
so yes
configure your IDE
Sorry meant to put on general
is your IDE actually configured? It's clearly not
the longer you spend here explaining why you aren't fixing your code editor, the longer it will take to help you
so go do it
There is no general chat in this server actually. You might get away with it in #💻┃unity-talk but it'll be up to the mods
See here
#531949462411804679 message
I meant code gen
Would that not work
No
It is not a code question, nor a unity question.
Can’t find mobile runner game template for tutorial in asset store, do I have to download 2021 editor version
Ok thanks
listOfPrefabs
listofPrefabs
this is not the same name, so yes, configure that IDE
In my script im making 2 gameobjects called leftcurrentBox and rightcurrentBox
Im trying to destroy them when they come into contact with my gameobject called 'Destroyer'
void OnTriggerEnter(Collider other)
{
if (other.TryGetComponent<Destroyer>(out Destroyer destroyer))
{
Destroy(leftcurrentBox);
Destroy(rightcurrentBox);
This is my code but its not working and the two gameobjects just go through the 3d object
My destroyer gameobject has trigger on, has a script attached to it
does your gameobject that is called Destroyer also have a Destroyer component attached? and have you confirmed that this code is even running?
A Destroyer component?
I might be miss remembering this, but I don't think OnTriggerEnter etc will fire if one of the object in the 'collision' does not have a rigidbody attached
How do you write classes? I want to make a Traits class and pass the parameters. Currently I have it like this which of course is wrong:
public class Traits
{
public float Speed;
public int[] Color;
public float[] Scale;
// Constructor for Traits class
public Traits(float speed, int[] color, float[] scale)
{
Speed = speed;
Color = color;
Scale = scale;
}
}
// Start is called before the first frame update
void Start()
{
public Traits balltTraits = new Traits(1.0f, {255,0,0}, {0.5f,0.5f});
//gameObject.GetComponent<Image>().color = new Color(255,0,0);
}
Both objects have a rigidbody
yes, the component your TryGetComponent is searching for
what's wrong about it, other than your array initializers?
Correct, it needs a rigidbody OR CharacterController
well, this is a class, but not a monobehaviour, so Start() will not work the way you expect
I do not quite understand your design here.
Is one a trigger?
Can you show us your hierarchy?
Yep
the class containing the Start function is not shown in the example
Why are color and scale arrays instead of being a Color and a Vector2 respectively
Your script references leftcurrentBox and rightcurrentBox, so it's presumably attached to some other object.
and it's not on the "Destroyer" object, beacuse it's searching for a Destroyer on the thing it hits
Thats what I thought the issue was but I dont know how to fix it
Are you replying to me here?
If so, I haven't stated a problem yet, so I do not understand.
this is the full scripts:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class BallScript : MonoBehaviour
{
public class Traits
{
public float Speed;
public int[] Color;
public float[] Scale;
// Constructor for Traits class
public Traits(float speed, int[] color, float[] scale)
{
Speed = speed;
Color = color;
Scale = scale;
}
}
// Start is called before the first frame update
void Start()
{
public Traits balltTraits = new Traits(1.0f, {255,0,0}, {0.5f,0.5f});
//gameObject.GetComponent<Image>().color = new Color(255,0,0);
}
}
the only thing wrong here is how you're intializing your arrays here new Traits(1.0f, {255,0,0}, {0.5f,0.5f});
this should result in a compile error because you cannot create an array like that
No I thought I was in dms with someone oops
I dont know I'm new to scripting so..
Then you need to start with some tutorials.
good way to start asking for help is by providing any errors you are seeing
When it runs, the two Obstacle(Clone) are created
You have a public inside a method
You can't have access modifiers for member variables
If that's not underlined in red in your IDE, you need to configure it. !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Is there anything wrong here making this not work?
What exactly is the issue with this
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
The reply chain goes cold, I don't know the original question
You've posted several messages without indicating what they're a reply to.
I can't do anything with this information.
When it runs, two gameobjects are created currentboxLeft and currentboxRight
I also have a 3d object called 'Destroyer' with a script called 'Destroyer' attached to it
I want my two gameobjects currentboxLeft and currentboxRight to be destroyed when they collide with my Destroyer gameobject
The two Obstacle(Clone)'s are the currentboxLeft and the currentboxRight
Okay. What is this code attached to? #💻┃code-beginner message
Hey, whenever I try to run my code, I'm getting this error :
Assets\Scripts\PlayerController.cs(28,21): error CS0103: The name 'movementVector' does not exist in the current context
well, movementVector doesn't exist, then.
Show your !code .
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
That code is in the script which creates the gameObjects leftcurrentBox and rightcurrentBox
What is movementVector
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerController : MonoBehaviour
{
private Rigidbody rb;
private float movementX;
private float movementY;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
void OnMove(InputValue movementValue)
{
Vector2 movementVector = movementValue.Get<Vector2>();
movementX = movementVector.x;
movementY = movementVector.y;
}
void FixedUpdate()
{
Vector3 movement = new Vector3(movementX, 0.0f, movementY);
rb.AddForce(movementVector);
}
}
Here is my code
What is movementVector
Okay, so why do you expect OnTriggerEnter to be called?
Actually, are you sure you copied the error correctly
Not sure, I just thought it would be
here's a screenshot of it
The error is correct.
Unity won't just call random methods.
I'm not sure actually, I'm going through the learn.unity project Roll-a-ball and I just stumbled upon that error
Let's thread this.
Ah, wait, it's a parameter, nevermind
Collisions
movementVector is a local variable in your OnMove method.
It doesn't exist outside of that method.
If you want to remember the movement vector so that you can use it later, you'll need to change that.
Oh ok I understand
Instead of declaring a local variable named movementVector inside of OnMove, you would add a field to the class
and assign to that field
I see what you mean, yet it seems to work for the one making the tutorial somehow???
Maybe I missed something
Most likely, yes.
They might have added the field after writing the FixedUpdate method.
I'm going to check back the video, I'll be right back
Ok it seems I'm quite stupid
Basically it's supposed to be rb.AddForce(movement); and not rb.AddForce(movementVector);
Ah, of course!
My bad and thanks a lot for pointing that out!
I didn't notice that either :p
similarly-named variables can get mixed up really easily
how do I make this gizmo cube the same size as my object?
If you set the Gizmos.matrix property to be the matrix of the object's transform, it'll move, rotate, and scale in the same way as the object
transform.localToWorldMatrix would be what you want
{
Gizmos.matrix = transform.localToWorldMatrix;
Gizmos.color = Color.blue;
Gizmos.DrawWireCube(Vector3.zero, Vector3.one);
}``` This is what I have
Is that a ProBuilder mesh?
yes
note how the transform's scale stays at [1,1,1] as you adjust the probuilder object's size
thats what is being used in the tutorial I'm following
yes
You will need to get the size from ProBuilder component, I guess
var mat = transform.localToWorldMatrix;
Vector3 size = new Vector3(1, 2, 3);
mat *= Matrix4x4.Scale(Vector3.right);
I ~think~ this would be correct
replace line 2 with something that actually gets you the size, of course
I have never touched ProBuilder components from code, so I wouldn't know what to do here.
How would I detect when a color changes and to play a sound when its detected?
Not enough information.
Where is this color coming from?
Explain what your game is doing.
this is what happened
you would also need to adjust the position, most likely
why do you need to draw a gizmo?
Bascially I'm using a sprite thats lerping colors from one to another. And I want to make it play a soundtrack when it changes to that colors hex code
Are you trying to play a sound when the sprite is finished changing color?
its for visualizing a gravity field
when it goes back to the original color. Like if it hits the dark color I want it to play night time music and when it hits the brighter color I want it to play the daytime track if that makes sense
I don't think you want to use the sprite's color at all.
I think you want to use the value that's controlling the color.
float time = 0.3f;
background.color = Color.Lerp(Color.white, Color.black, time);
I presume your code is a bit like this
yeah
look at time, not at the color
close enough
use the value of Mathf.PingPong(Time.time * speed, 1.0f) to decide what music to play
I would store that in a local variable
then use that to:
- calculate a color
- pick a song
There's no reason to try to figure out what music to play based on what color you got
hi im very new to unity and the discord (so direct me if this is the wrong channel please).
when i try install unity the 'editor application' fails saying "validation failed". i have run as admin, turned off my antivirus, reinstalled unity hub. any other suggestions would be incredibly useful!
Have you restarted your machine at least once?
yes i had to do that to turn off my anti virus unfortunately
i have vscode installed prior do you think that would be an issue?
no, that is irrelevant
If you're having persistent problems, check the log files. Scroll to the end and look for anything that looks like an error.
I think it's... !install ?
- Make sure you have enough space including on
C:drive. - Check that it's not being blocked by antivirus/security programs.
- Look through the logs for a real reason why the setup fails they are pinned [here](#💻┃unity-talk message).
If you still have issues, perform a clean install in another location:
- Install the Hub and Unity in a non-system drive or a clean new folder in the root of
C:drive. - Failing that use the recovery Refresh option or reinstall OS entirely then repeat the previous step.
yep
note that you should ~not~ need to run this thing as an administrator
also, this isn't a code problem; you should ask further questions in #💻┃unity-talk
thank you i'll try look through logs
will do
Hey so I'm new to Unity and am trying to spawn meteors on a random x axis but whenever I try and run the game with the script in it gives me this error. Is there a specific reason why? Any help would be greatly appreciated
remember that it is case sensitive
use nameof to avoid easy mistakes like these, nameof(Spawn) will evaluate to "Spawn"
Okay thank you, I will try that
Huh, I never knew, thanks for sharing
Oh my god it actually worked
Thanks so much for your help, I suppose it's because the course I'm following along with was made using an older version of Visual Studio
just realized all my SO's are always marked as Serializable, will removing it potentially do any harm?
I never use System.Serializable on ScriptableObjects, and I haven't encountered any issues.
Worst case u just have to undo changes in git
Pretty certain it's unnecessary.
Monobehaviour also don't need the attribute.
And if I remember correctly, you can't have either as a serialized field other than an object field because Monobehaviour and SerializedObject don't have serializable attribute. So you can't make it like any serializable structs or non unity objects.
Normally you can't do that with unity objects but I think I remember forcing it through custom editor and got errors.
Hi, can somebody help me with making a 2d lever change scenes?
What do you have so far?
So I’m extremely new to coding, and my goal is to make my player object move around in key inputs by the end of the week, how do I do that, I know it needs to be like
if something about keypressed down
Then transform x,y,z
But I don’t know the specifics, can anyone explain?
Literally any beginner tutorial shows how to do that
I tried following one in the unity website and it didn’t work, but also I’m more interested in learning how it works as opposed to what to type, so I can apply that info later
Show your code and explain the issue and someone can tell what the problem is
Ok will do once I get back to my pc, thanks
this is what I have and its for outputting a textline to the debug log on w press
i believe i need to define GetKeyDown(KeyCode.W and Debug.Log globally but i genuinely dont know how
the unity learn guides should be teaching you how it works, they are not resources for you to just copy paste without learning. If it didnt work, you should specify what didnt work
also !code for formatting
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
the text did not output to the debug log, I also didnt just copy paste, ill go re-read but as far as i know, its basically something i dont know how to search for, basically idk what the concept im missing is called
also will do this in the future
do it now, dont do it in future
do you have errors in your console?
actually nvm i read the code more carefully
you have 2 classes there, you dont need KeyCodeExample
gotcha
Oh jeez I barely caught that he defined a subclass in there.
If you assign move to a game object, there is no KeyCodeExample created. KeyCodeExample is not created or initialized in move. (you also shouldnt really do this with classes inheriting from monobehaviour)
KeyCodeExample should be in its own file
if you want 2 classes that is
// using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class move : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
public class KeyCodeExample : MonoBehaviour
{
void Update()
{
if (Input.GetKeyDown(KeyCode.W))
{
Debug.Log("W was pressed");
}
}
}
}
is this correct?
is ``` (the char on top of Tab)
i was missing one sorry
No you still have that KeyCodeExample class inside your move class.
i meant the way to format it ima go edit the code now
ah kk
wooo its workin! i also realized I had 2 too many curly brackets, thanks yall
No problem, but please make sure to understand WHY it worked.
I believe I do, the brackets for one were out of place, and secondly, the key code example was a subclass that just didnt need to exist correct?
There's an age option in the game, and i want the character to randomly die between the ages of 80-100. but currently its always dying at 80 doesnt go further. Whats the issue?
Try logging your random death threshold and see what values your getting, compared against your death threshold, also, where are you executing that function? Is it something that happens once/on an event or constantly/in update?
in update
yep that was the issue
fixed it
lmao im so dumb
Can you help me fix one more thing pls?
https://hatebin.com/uablqiggtq how can i stop the two types of events i have in this script from overlapping each other (occuring at once) the two types are supernatural events, and regular events
ok so I have been working on my code for a bit and, it works how I want it too now, aside from tunneling instead of collision occurring at high speeds, the sphere has this script attached and both the sphere and wall have a rigidbody on them, any advice on how to fix the tunneling? I think the solution is to jsut make movement slower, as my project dosent need particularly fast movement, but if there is a way to completely just stop the tunneling, I would like to know, for future issues
i apologe for asking so many thingems here
Please use a paste site for large blocks of code
!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.
got it i apologize lemme do that
Not sure what you mean by tunneling, but using update with rigidbodies is usually a sign of doing something wrong
use debugger, step through line by line
How should i do smooth movement, I kinda knew it was wrong, but I did not know how to figure out the correct way
a powerful website for storing and sharing text and code snippets. completely free and open source.
I'm actually not even sure this example is 100% correct since it's doing input in fixed
what does fixed do as opposed to regular update?
you are using GetKey which fires for every Update the key is held down so you are probably adding too much force
@buoyant prawn
- Update and FixedUpdate run at different tickrates, FixedUpdate is separate loop tied to physics "steps" which can happen multiple time per Update or none at all, depending on settings
- Use Update to store input into booleans, use that input in FixedUpdate
- To stop tunneling
3.a - dont disrupt physics steps by moving objects with transform, use forces instead
3.b - change rigidbody collision detection mode to continous - For it to be smooth, enable interpolation on rigidbody, it means the transform will be smoothly adjusting to actual physical position between physics steps
- Do not directly parent the camera to the physically controlled object
So i have done 3. 4. and 5 in this, but thank you for the update/ fixedupdate info
is there an alternative to GetKey to make it only fire once?
GetKeyDown
Hi so i have an issue in my game so for context, my game is a multiplayer fps game, and the issue is about the button. You see if someone creates a room affter a few seconds a button is instatiated and if you click the button you join the room. But my problem is the button/buttons have a text for the roomname but it is too far to the left side the button, and when the button is instatiated it is parented to a gameobject so i tried moving the parent object, but when i pressed ctrl + s to save it reset the position please help
gotcha
Down/Up/ and GetKey is "being held"
You can cap the amount of force too if that's what you're looking for
i would like to know how to do this, but I would prefer it only fire the speed once
when adding force you can select which force mode to use
read which each of them does
private void FixedUpdate()
{
//cache this eventually
var sqrMaxVelocity = MaxVelocity * MaxVelocity;
var v = RigidBody.velocity;
// Clamp the velocity, if necessary
// Use sqrMagnitude instead of magnitude for performance reasons.
if (v.sqrMagnitude > sqrMaxVelocity)
{ // Equivalent to: rigidbody.velocity.magnitude > maxVelocity, but faster.
// Vector3.normalized returns this vector with a magnitude
// of 1. This ensures that we're not messing with the
// direction of the vector, only its magnitude.
RigidBody.velocity = v.normalized * MaxVelocity;
}
}
Some project I was working on. Probably not 100% correct as I probably snipped it from stackoverflow/unity forums ;)
take into account that this directly modifies velocity, any bumps that would physically change the trajectory will be overriden
I don't use rb that much; I just needed to prevent some objects randomly being flung into the skybox
thank you both!
is there a better way to move things that I should look into than rb? these little wiki pages for terms are extremely helpfull
hey guys. I am using that code to move a lot of things and it works fine. But now I added it to a new object and it is not working. ANy ideas why would be? ```cs
private void BossMovement() {
float dist = Vector3.Distance(_player.transform.position, transform.position);
Vector3 MoveDirection = _player.transform.position - transform.position;
MoveDirection.Normalize();
_rb.velocity = MoveDirection * _speed;
}```
if you want physics you use rigidbody
what is the value of speed?
the alternative to that is to use third party physics system, which is probably over your head
LOL, I didnt give a value to it. Damn sorry just woke up
👍
please anyone?
You'll need to provide some better explanation.
have you log Why the superXXX and regular event are triggered at same time
Well okay
events are basically just set the panel gameobject to active
i have two types of events, regular ones which need to keep happening, and supernatural ones from which one needs to be randomly selected and occur only once in a character's lifetime. That all works as expected i guess but the problem is sometimes both the regular and supernatural events happen at once, meaning two panels enabled at once, which makes the game unplayable until you restart
supernaturalEventOccurredThisYear = false;
if (currentYear != previousRegularEventYear && !supernaturalEventOccurredThisYear){
TriggerRegularEvent(currentYear);
previousRegularEventYear = currentYear;
}
if (currentYear != previousSupernaturalEventYear){
TriggerSupernaturalEvent(currentYear);
previousSupernaturalEventYear = currentYear;
}
```you have set the supernaturalEventOccurredThisYear =false
so your code can be simplified as
if (currentYear != previousRegularEventYear){
TriggerRegularEvent(currentYear);
previousRegularEventYear = currentYear;
}
did you use the debugger?
and the two boolean guards:
if (!eventOccurredThisYear && !supernaturalEventOccurredThisYear)//in regualr
if (!supernaturalEventOccurredInLifetime && !supernaturalEventOccurredThisYear)//in supernatural
```can also be simplified as
```cs
if (!eventOccurredThisYear)
if (!supernaturalEventOccurredInLifetime)
```so, no any guard to block the supernatural event happening after regular event happened
and there is a simple way to solve this, swap the two triggerXXX in update
i dunno what you mean, sorry
the boolean guard is "supernaturalEventOccurredThisYear" variable and the only method set it to true is triggerSuperNXXXX so you can just swap the two triggerXXXEvent method
like put the TriggerSupernaturalEvent before TriggerRegularEvent?
yes, let it executes earlier
okay well i did that, issue isn't fixed
oh i mean swapping the two if blocks, not just the method calls, forgot to say that
the check of supernaturalEventOccurredThisYear should be done after TriggerSupernaturalEvent
debugger is not scary, its easy to use
do you mean Debug.Log? i cant find anything in unity called a debugger
In your ide(visual studio for example). There's a tool/feature called debugger. It allows you to pause and step through your code along many other convenient features.
Check the Debugging section in the pinned messages.
Hello, I am having trouble moving my character, this is the error,
!code - show your code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Line 62 is probably trying to access a child transform, and there aren't any
Vector3 endPosition = waypoint.transform.GetChild(0).transform.position;
There is no child
how do I add a child?
by dragging a gameobject onto another gameobject
ok whats that suppose to be regarding this 2D Fantasy Character pack?
I should rename it to Player.
It's your project and your code. We don't know what it's supposed to be.
I need to know how to create a player with the use of a asset given character model, from the asset store.
in 2D mode.
Any links or suggestions?
Maybe look up a tutorial on how to use sprites
I did those. But this is some other script type that has shooting a magic spell it's suppose to be.
Do I have to purchase this guys pack is why?
It's a demo
Nobody knows what you're looking at so not sure how anyone can actually answer that.
If there's a sample scene in the asset, run it and see how it works?
That one.
There is a sample scene.
Run the sample scene.unity and explore how they made it work.
I found in the scene underneath the mage role object has a shadow I added to the scene.
The scene in Unity 2D Asset, is only showing a film to be played.
There is no video files listed in the package contents ...
It's known as "scene"
A scene isn't a film
if you play "scene" it opens a game that is just a film.
No, it's not
It's a scene, that when you run it runs the scene. The point is to look at the objects in the scene and see how they set up their animate.cs component.
I did check around it, I will check the animate again.
Good luck 👋
can someone help why it isnt showing the text like in inspector I cant drag the text under button
[System.Serializable] public class ButtonData { public Button button; public Text buttonText; public string normalText = "CHANGE"; public string ownedText = "OWNED"; public int cost = 0; public bool isOwned = false; }
explain better
What does it show instead?
like in inspector I cant drag Text UI to the desired field I want
Are you using TMP?
Yes
public TMP_Text buttonText;
thank you!
Text is the legacy text component
Just a sanity check: isn't Vector3.Normalize() equivalent to Vector3 = Vector3 / Vector3.magnitude?
Yes
In other words, to normalize a vector, simply divide each component by its magnitude.
Okay so I do have a big bug somewhere and it's not just me mis-remembering the doc. Thanks.
I tried to add a Tag to a GameObject but since it wasn't predefined in Unity it didn't work. Can I use C# to predefine tag types?
Only if the magnitude is greater than 0
You cannot. Just put a component with a string field on the object instead of relying on tags
I recommend not using the Unity Tag system, instead write your own scripts and add them to the gameObjects.
I.e. you add an 'Enemy' script to a gameObject. To see if the GO the player hits is an Enemy you use:
if (TryGetComponent(out Enemy enemyScript))
{}```
You can also make an interface:
```cs
public interface IHitable{}```
and have your Enemy script inherit from it:
```cs
public class Enemy : MonoBehaviour, IHitable```
Then you can look for a IHitable component. That allows you to group tags together and makes it easy to retrieve the correct component.
Yeah, that was the bug.
Was doing a bunch of distance check between objects and forget to filter for self-check, which result in a null distance.
.Normalize could handle it but /.magnitude was creating non-sense values that created aberrant results further down the code.
Will try
Hello, I want my game to save it's state when the application is paused and this is how I implemented it, Is this correct?
Depends what your definition of "paused" is https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnApplicationPause.html
Is using SimpleJSON included in 2019 but not 2020?
Why would a Python library be included in Unity?
You can download Newtonsoft as a Unity library and use that for serializing/deserializing JSON
A project i just got from a collegue has that in the "using" area, and has JSON.Parse, but im using a different unity version and all, so i was wondering if its bc of that
Oh, there are a ton of SimpleJSON libraries, not just Python
Well I never heard of it but as I said, you can very easily migrate to Newtonsoft either way
I just need an altrernative for the JSON.Parse since it doesnt exist in my own project
Just how it was implemented in the docs, but what I see is that they assign it to a variable outside of the method, can't I just do the savegame inside the OnApplicationPause method?
why i cant use SetActive on multiple objects? (private GameObject[] hideObjects;)
it is an array of gameobject
Because you don't set a gameobject as active. You set the component in it as active.
is it in the asset store or
I think you can just use a foreach method to do SetActive on each gameobject
ohhhhh is it in NuGet
Then I think you can just put all your UI elements under a parent GameObject then just SetActive the Parent Object, no?
nope, there is much more things, it will broke if i use this method
it wont install them 😔
How can I handle going up on slopes with SphereCast?
i almost got heart atack when i entered #archived-code-advanced
why
sure you can do whatever you want in there.
im code begginer...
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using TMPro;
public class PlayerController : MonoBehaviour
{
public float speed = 0;
public TextMeshProUGUI countText;
public GameObject winTextObject;
public TextMeshProUGUI speedText;
private Rigidbody rb;
private int count;
private float movementX;
private float movementY;
public AudioClip triggerSound;
private AudioSource audioSource;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
count = 0;
SetCountText();
winTextObject.SetActive(false);
audioSource = GetComponent<AudioSource>();
}
void OnMove(InputValue movementValue)
{
Vector2 movementVector = movementValue.Get<Vector2>();
movementX = movementVector.x;
movementY = movementVector.y;
}
void SetCountText()
{
countText.text = "Count : " + count.ToString();
if(count >=12)
{
winTextObject.SetActive(true);
}
}
void Update()
{
float speed = rb.velocity.magnitude;
speedText.text = "Vitesse : " + speed.ToString("F2") + "m/s)";
}
void FixedUpdate()
{
Vector3 movement = new Vector3(movementX, 0.0f, movementY);
rb.AddForce(movement * speed);
}
private void OnTriggerEnter (Collider other)
{
if(other.gameObject.CompareTag("PickUp"))
{
other.gameObject.SetActive(false);
count = count + 1;
PlayTriggerSound();
other.gameObject.SetActive(false);
SetCountText();
}
void PlayTriggerSound()
{
if (triggerSound!= null && audioSource != null)
{
audioSource.Stop();
audioSource.PlayOneShot(triggerSound);
}
}
}
}
Hey, I have an issue with sound today. Basically, I wanted to pop a sound whenever an object was collected by the player, but I can't seem to make it work. Here's the code :
!code for the correct way to post lots of 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.
And you're probably not getting past the if condition in PlayTriggerSound()
or the if condition in OnTriggerEnter()
You need to debug it to see where the code execution reaches
is there a bug within unity currently? Everytime I create a script it says "no monobehaviour scripts in the file unity" so I have to rename the script, then rename it back to what it was so that it registers???
how are you creating the scripts?
from your IDE? From Unity?
From unity
then opening them in microsoft visual studio
then when I save it
and go back into unity
it says no monobehavour like it hasn't synced
Are you changing the name from VS?
You can cast a sphere from the center(ish) of your character, downwards and a bit towards the movement direction.
The hit will give you
- a normal which you can use to rotate the movement direction and check if the angle is too steep
- a position so you can check the height
This stuff (custom movement) can be a bit complex though. You need some tweaking and its important to visualize what is happening
Anyone know a video that teaches you how to make a first person player controller similar to games like phasmophobia, lethal Comapany, and escape the Backrooms ?
They all have a rather similar player controller
what with like the bending and stuff
What makes those games control different? I never played any of them
like when u look down in phas your whole body moves and the cam is actually in the eyes and doesnt just rotate down
phasmo character controller janky
Sure how can I visualize a capsulecast?
Nvm I got it , thx doe
Was talking about spherecast, but anyway probably a combo of Gizmos.DrawWireSphere + Gizmos.DrawLine
One important thing to know about SphereCast is that the hit.distance is not the same as the distance from the origin to hit.point.
It is the distance that the sphere moved
Nope...
Have you tried right mouse click -> reimport? Probably a quicker way to do it
That's not a solution to the overall problem, just a quicker way to get the script working
so you aren't on macOS, then
I have had some ~weird~ problems when changing the case of a file name, because macOS's file system is case-insensitive
MacOS has VS 🤔
it has "visual studio"
Yes
Unity doesn't quite notice the change. It winds up failing to compile the file.
case-insensitive filesystems my extemely unbeloved
so there's a chance, yeah
oo that might be beter
nah Windows 11 pro
Was happening in college too... so might just be this project weirdly
either way, project deadline is tomorrow so oh well
I would try this.
I have occasionally had Unity miss a file change. Deliberately reimporting the file helped in that case.
In what context? If you are dealing with individual angles, the correct method would be SmoothDampAngle
If you're trying to smoothly rotate towards a Quaternion, then that would be inappropriate
var leftStick = inputSystem.gameInput.Gameplay.MoveCursorMap.ReadValue<Vector2>();
Vector2 anchoredPosition = cursorTransform.anchoredPosition;
anchoredPosition.x += leftStick.x * cursorSpeed * Time.deltaTime;
anchoredPosition.y += leftStick.y * cursorSpeed * Time.deltaTime;
cursorTransform.anchoredPosition = anchoredPosition;
I am moving my crosshair on gamepad using the left stick. Now, how do I detect if I am over an button (UI) element with that crosshair (cursorTransform)?
you could fire a raycast from that position
cursorTransform.anchoredPosition += (Vector3)(leftStick * cursorSpeed * Time.deltaTime)
is the same as what you wrote, but shorter
how so
raycast only works with colliders afaik
UI elements doesn't have colliders
is it correct using it this way? or just put it on void start
if you click loginButton multiple times it will add multiple listeners to that onclick event
i don't find that much resource for addlistener meaning, can you explain what it is?
you need to use the EventSystem
https://docs.unity3d.com/2018.1/Documentation/ScriptReference/EventSystems.EventSystem.RaycastAll.html
or GraphicRaycaster
https://docs.unity3d.com/2018.1/Documentation/ScriptReference/UI.GraphicRaycaster.html
You use AddListener to say "when this event happens, tell me about it"
It doesn't makes sense to add a listener every time the login button is clicked
use a virtual cursor
don't use a hack
should I prevent monbehaviour functinality if the monobehaviour is disabled? for example,
public class Damageable : MonoBehaviour
{
[field: SerializeField]
public int Health {get; private set;} = 100;
public void Damage(int damage)
{
if(!enabled) return;
Health -= damage
}
}
thank you didin't know about that
I wouldn't, personally.
If I tell something to take damage, it'd better take damage
But I can't come up with a concrete reason beyond that.
Should be writing your code in such a way that this method can't be called when it's disabled.
EG: Damage wouldn't get called on this because the collider is also disabled so there would be no physics events to start the flow off
Yeah.
got it!
i see. thx
god I just realized how it's work, have to read it again a few time, it isn't that complicated actually
Hey, can anyone share some insight into what affects a Physics.OverlapXNonAlloc performance, regarding the size of the space, total objects in the space, objects of given layer in the space, anything else?
What is better for spaceship shooting mechanics, raycast or physics based shooting?
Hello. Am i doing something wrong when calling this method? LaserSource Script calls the Laser script method.
GetComponent can return null
Does the object with the Laser script on it have a LineRenderer
Yes sir it does have a LineRenderer 🙂 @polar acorn It broke after i refactored the code a bit
assign the line renderer directly if possible
You're getting the component in Start but you're calling DrawLaser immediately after creating it. Start runs at the beginning of the frame
So it hasn't run yet
Make the field public and drag in the reference
This works so the lineRenderer seems fine @polar acorn
what field?
lr
that should go in Awake
I will try that. was reading about that before.
Better to just have the object already know its line renderer before it starts at all
by assigning it in the inspector
Your solution worked. I never thought it was necessary to reference a component inside an object that way.
If you can use the inspector you should use the inspector. GetComponents are much slower than a manual assignment
you should only use those in situations where a direct reference can't be done
Indeed. Use it when:
- there is no way to assign the reference ahead of time
- the reference is so unambiguous and obvious that it'd be a waste of time to assign it
(your threshold for the latter should be very high)
I mostly do that when I have a component that must be parented to something, like an entity
Hey guys, if I have an object called boss, and I have a child empty object with only a collider 2d set as isTrigger to ON. I also have in the child a tag. I am using that tag to check for collisions but it is not working. Why?
Does the boss have a rigidbody2d?
- Use CompareTag, not
==to check tags https://docs.unity3d.com/ScriptReference/Component.CompareTag.html - Show the inspector of this object and the thing that it's colliding with
That is fine
The onTriggerEnter method is on my enemy script.. i just dont want the enemies to overlap the boss. But I want in a bigger area that is why i added a child to control the area with a collider
You have two namespaces imported that both have a class named Text
And the other?
ah it auto did that 😂 Thanks
What other? u want to see inspector of the enemy ?
The thing with this script on it
its the enemy that contain the ontrigger method
When I open my script, intellisense is not working and the expolorer tab is empty
Okay, so, neither of these objects have the tag "AreaOfTouch" so the code is doing as it's expected to do
and not logging
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
VSCode has a tendency to just die randomly. Hit the regenerate project files button
Where is that 😵💫
if (other.CompareTag("BossAreaOfTouch")){
Debug.Log("Emeny touched the Boss Area");
}```
On the screen you just sent a picture of
Okay, so does that work now?
No
Show the full !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.
You say VSC but both screenshots show VS
and that script editor has (internal) at the end
that implies that you don't actually have the "Visual Studio Editor" package installed
alternatively, it implies you have a compiler error that's preventing it from activating
!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)
Oh. @polar acorn you mean the Unity editor
I thought you mean vscode
I meant this screen that you send a picture of
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
No
also, nitpick: i would not put my git repos into the OneDrive folder
just feels like you're asking for OneDrive to do something that confuses Git
This is not correct
You don't need that or want it
Follow the instructions for VS Code.
You should follow the instructions. That is a legacy package that doesn't work as well.
You should also follow the instructions.
The package is installed in the Unity editor.
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
It lost support on august 6th
Now both use the Visual Studio Editor package
it's been deprecated for a looong time
Both of you should not be trying to "DIY" this. Just follow the instructions.
you'll just give yourself a headache otherwise
I meant that specific one. Microsoft finally made their own extension on august 6th (I think. It was august at least) and that was the final nail in the coffin of that package. It worked mostly up until then
Ah, I see.
Thanks
The new package gets rid of some weird restrictions that made Code's analysis slower
i am noob. how do i change color of text
its a basic text mesh pro text but i dont see color option
pretty sure there is a color option on text prop
in the code?
ah i am dumb wrong chanel
but why it doesnt change to red, it stays black now that we started?
you might have wrong shader somehow
hmm probably
make a new TMP text object
|base color should be white
see difference
when i change color there, all texts change color and i just want this particular one
you dont change color there
you make the base color white
then change it where it was red
dude this is a code channel
i love you, its solved. ty boss
so why dont you ask about that
the animator has parameters that can trigger different transitions
Hey so I've got an issue with a ScriptableSingleton, maybe this is not how you use it?
So in Unity, I have this StarterDeckDefinition which is a ScriptableSingleton.
It has a private serialized field, in which I set the values via the use of the Unity inspector (!).
So technically, the field is null, but it's filled by the Unity editor just like any other ScriptableObject.
However, when calling Get() to actually get the starter deck, the field is asserted to null.
This is the line calling the ScriptableSingleton:
public DeckService()
{
Instance ??= this;
LogInfo("Successfully set the DeckService's singleton instance");
LogInfo("Now retrieving starter deck definition");
_deck = new CardPile(StarterDeckDefinition.instance.Get(), true); // <------
LogInfo("Deck has been set and shuffled");
LogInfo("Deck consists of these cards:");
if (debugMode) _deck.Pile.ToList().ForEach(card => Debug.Log($"\t- {card}"));
}
Is this not how you use it?
Show your test code?
Hey, does anyone know how to add functionality to scriptableobjects? I have an inventory that takes an item SO which has name, description, item cost, model. I can assign it to my inventory but I'm not sure how to add unique effects to each item. For example one item would heal health, one would recover mana, add movespeed, etc. but im not sure how to go about this.
The message is telling you exactly what's wrong and how to fix it
You need only to read it
Hold the affected stats in the item so, whether that be an enum or whatever a stat is defined as. Inventory loops over all the items
Also it not a good idea to keep Unity projects in a OneDrive folder, this can cause problems
Oh I thought I have git installed. Let me try to install it
it's not in onedrive but the ThisPc/documents folder. However it also exist in onDrive
That sounds good but what if the item doesnt do anything to stats for example? Like it has a function of a grenade
You can still declare functions in an SO, but you'll maybe have to declare a new SO which inherits from your old one. Or you provide it this functionality in the form of a delegate. Regardless this method has to exist somewhere
I created a method that subtracts the percentage of the victim's armor from the damage that was applied to it. Works correctly with any percentage of armor exept 100%. If I give a 100% armor to enemy method output very strange number. Can you say where is the problem? (On screenshot is shown result of this method)
private float CountDamageArmor(float damage) { return damage - damage * Armor * 0.01f; }
I'll try out the delegates you suggested. Thanks!
This, is scientific notation of a number. It's very close to zero right now. The e-07 means there's around (my math is rusty) 7 zeroes before the 4 here: -0.000000447
You can format the text with damage.ToString("F0") to not display decimals. Adjust the number after the "F" to show more or less decimals
several options here
In this case, you're discovering the power of ~floating point imprecision~
damage - damage * 100 * 0.01f should just be zero
but due to slight errors, it's not exactly zero
I would suggest clamping damage to 0 anyway. You wouldn't want 200 armor to make an enemy take negative damage..
alternatively, use armor scaling that doesn't need a limit!
damage * Mathf.Pow(0.99f, armor) would reduce damage by 1% for every point of armor
Any armor formula that involves addition or subtraction will need to be clamped so that it doesn't go into wacky negative values
note that this formula causes enormous damage when enemies have negative armor (if that's even a thing you're going to have, of course)
It just does new DeckService() to test if it is working
are you supposed to actually create an asset out of a scriptable singleton?
i've never done it that way
Isn't that the point of a scriptable object? But maybe I've approached it wrong, this is the first time I've used it
sure but where?
In a [Test]? [UnityTest]? Also did you create the singleton asset?
using System.Collections;
using main.service.Turn_System;
using UnityEngine.Localization.Settings;
using UnityEngine.TestTools;
namespace test.EditMode.Turn_System
{
public class GameTests
{
[UnityTest]
public IEnumerator Sample()
{
// Adds the first locale as the selected locale in CI executions
LocalizationSettings.SelectedLocale ??= LocalizationSettings.AvailableLocales.Locales[0];
// Create a new game
new DeckService();
yield return null;
}
}
}
Yes this is the asset
I think you're supposed to use [FilePath] as per the example https://docs.unity3d.com/ScriptReference/ScriptableSingleton_1.html
That's one major use of scriptable objects, yes
But they're really just a way to make a unity object that doesn't have to be in a scene or attached to a game object
Also, these are intended for use in the editor only.
They're in UnityEditor
This is not the appropriate use-case.
But I do have just the thing for you...
using UnityEngine;
public abstract class SingletonSO<T> : ScriptableObject where T : SingletonSO<T>
{
private static T _instance;
public static T Instance
{
get
{
if (_instance == null)
{
_instance = Resources.Load<T>("SingletonSO" + "/" + typeof(T).Name);
}
return _instance;
}
}
}
This is how I create "singleton scriptable objects"
Ohh so not CreateAssetMenu like with ScriptableObjects?
i mean, you can do it
but Unity doesn't care about those assets at all
All of the SO assets go in Resources/SingletonSO/
here are mine
Yeah I think ScriptableSingleton solves this same problem though
allegedly
at least in the editor
I'm confused, this is exactly what I want: I just want to define one ScriptableObject which contains the set of cards. This should be a singleton so I can acccess it -> why not use a ScriptableSingleton?
Because ScriptableSingleton doesn't work the way you think it does.
Well one thing is that ScriptableSingleton is editor-only
It doesn't look for a single instance of an asset of the appropriate type and give you that
That is not what it does.
Read the documentation.
it exists so that you can remember data between recompiles of your game -- and, if you specify a file path to serialize to, between editor sessions
https://gamedev.stackexchange.com/questions/186861/what-is-use-of-scriptablesingleton-in-unity explains it really well
I have a question. Does void OnCollisionStay() get called after or before void Update() and if it is before is there any way to make it get called after it or otherwise some way to check for collisions on demand?
The important thing with the code above is that the asset's name must exactly match the type's name
so if it's a FooBar, the SO asset should be named FooBar
before
neither. it's called during physics updates.
This shows where it's called relative to update^
note it doesn't run every frame, only on frames with physics updates
I don't believe you can ask for unity to immediately check if you're currently overlapping another collider
~but~ you can use the Physics.Overlap* methods to check if there are colliders in an area
2D physics allows for this.
just use OnCollisionEnter and Exit to track the colliders you're touching in a list or set
and check that list in Update
Not sure if this counts as part of the scripting section or whether it is beginner or not, but can I get a little help with something? I tried opening up a project of mine, but it never would. Tried looking at task manager and restarting my whole system. Nothing worked so I eventually deleted Unity Hub and the version of unity I was using. I reinstalled the hub and downloaded the newest version of unity (2022.3.13f1). I am now able to open my project and everything works correctly except the "Starting Selected Interactable" of all my sockets. I know upgrading my engine isn't the best idea, but I found a blog post where someone was having the same issue. I even tested my issue with trying to move things in the editor while the simulation is running, and it seems my problem is exactly like theirs. I can link the blog if needed.
what is "Starting Selected Interactable"?
this is the bake that u asked i think
Part of the XR Socket interactor. Part of basic VR development
show vidoe of issue, and do you have a script or something on enemy?
does it still happen if yu disable the script?
let me try
also put pause mode when it disappears, then inspect scene view see where it is
*sorry I haven't replied back to any of the answers I'm just kind of confused about what I'm trying to do right now thanks for helping though
it gives me this error
NullReferenceException: Object reference not set to an instance of an object
PlayerMovement.Start () (at Assets/Scripts/Player/PlayerMovement.cs:36)
not sure thats related to navmesh agent
something you should stil fix
then there is no other error
ur floor is moving or something is moving the navmesh surface
just notice u have navmesh surface component on enemy/agent
thats wrong
it goes on the floor
then rebake
Hi, how do I ensure one of my variable properly references a PREFAB through script (as if I dragged it from my folder to an unity window variable) please ?
thank you the enemy does not fall now thanks
might wanna fix that error too (#💻┃code-beginner message)
https://unity.huh.how/runtime-exceptions/nullreferenceexception
ill work on it thank you so mutch
Dependency Injection..sorta
Drag it from your folder to a unity window variable
the Unity way
If that was possible I would have done it lol
Why isn't it possible
Why does that matter ?
kinda does
Because that's the solution
It isn't, because it's not possible
Why is it not possible
prob a prefab and they want reference obj scene or sum
But they want to reference a prefab, specifically. Which means it's available everywhere to be dragged in, even other prefabs
true , idk some people dunno what prefab is for lol
I am trying to create a 2D shmup that incorporates basic math. As you can see from the screenshot, a random number will appear as the "answer" to a simple math problem that the player solves by shooting asteroids with random numbers on them. The problem is trying to make the numbers I shoot transfer to the problem. Right now I am receiving the following error:** NullReferenceException: Object reference not set to an instance of an object
bullet_Script.Start () (at Assets/game_Scripts/bullet_Script.cs:17)
** on this script https://hastebin.com/share/naruhukapa.csharp. Any advice on how to correct this?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
is math_generator on the enemy? Or the enemy_generator?
You shouldn't really use find for that either way. Just drag and drop a reference
Pretty clear. Line 17 is this:
generator = GameObject.Find("enemy").GetComponent<math_generator>();```
This can only throw a NRE if the "enemy" object is not found in the scene
From your screenshot it's clear there is no object in the scene named "enemy" @grand birch
It is, you quite literally just drag it. Now if you are trying to get an object to reference its own prefab, that reference will update to be the instantiated object so you'll need to plug it in another way.
Except it's not a serialized property that can be displayed in the editor
I dunno why you assume that dragging it is the solution when I specifically ask for a case where it isn't the solution
which is exactly what I want to do
ok so
copy it from somewhere that is serialized, or use Resources.Load or Addressables
those are more or less your only options
I ended up using Resources.FindObjectsOfTypeAll then filtering by name
that's quite inefficient
it is
why not just use the name directly in Resources.Load
Why do that when you can serialize it and drag it in?
or that^
Why can't you make it serialized
I suspect this is just a case of someone who "hates" the inspector
Not quite
turns out that behavior is "by design"
https://issuetracker.unity3d.com/issues/ontriggerexit2d-is-called-after-exiting-play-mode-when-trigger-colliders-overlap
So, why not actually say what the problem is
Because there is no problem ?
wait I thought disabling colliders didn't trigger this stuff? Is that new? 2D only?
I'm just asking for a specific way to do something that isn't dragging it
why they want OnTriggerEnter2D to be called after Application.quitting has already been invoked but apparently don't want the same behavior for OnTriggerEnter is beyond me though 🤷♂️
Okay, so you can just serialize it and drag it in then if there's no problem with that
i guess that was a bug and they want it to trigger OnTriggerEnter2D, even if the collider is being disabled because the scene is unloading or the application is quitting.
and yeah, it is only 2d for whatever reason
We do not understand why you can't just serialize the field.
It's just odd that you don't want to use the most simple and performant way of doing it. I think they're just really curious
You must explain why instead of just saying you can't
And you do not need to understand that to answer the question
Asking about your attempted solution rather than your actual problem
please read this before wasting our time further
Alright then keep your secrets
this is a patently obvious XY problem and it's kind of infuriating to read the chat logs
Until you say why you cannot serialize the field, the problem is solved. The solution is "Drag it in"
until you've specified why that doesn't work, your problem is solved
Right. The enemy_generator object spawns the enemy objects at random X coordinates that fall towards the bottom of the screen. The math_generator is part of the UI and will be where the data for the math problem at the bottom of the screen will be stored.
"I would like something that tastes like fries, but we don't have potatoes here, any recipe ?" "just buy potatoes lol"
that's strange, what do you think about his solution? where he says to disable https://docs.unity3d.com/ScriptReference/Physics2D-callbacksOnDisable.html
The way they repeated "it's not possible" made me think of American Psycho, the scene where the guy says
Why isn't it possible?
It's just not.
Why not you stupid bastard
Just answer the question.
But in this case you DO have potatoes
Why can't you just make a serialized field?
We might be able to help you if you actually explain the situation to us.
More like:
"No take, only throw"
Perhaps this is something static? I don't know!
And you do not need to
Then you don't need another answer
Yes you aren't
You've got a perfectly good one
Glad you figured that one out
nobody else will be interested in helping you either
Serialize the field, drag it in
fix your attitude or leave.
Leave
Says the guy looking for a fight
My sibling in christ they're looking to solve your problem
Thanks @wintry quarry btw, I tried Resources.Load first but it didn't work, not sure why it worked after renaming my prefab
you're being rude to people trying to help you.. thats rude
i'm gonna be honest, i didn't even know that existed until now. might as well use it though if you don't want those messages sent on quit 🤷♂️
My question was (paraphrased) : "Is there a way to reference a prefab without dragging it in ?", you do not need any other information to ask that question, do you ?
I assume you simply did something wrong with how you called it. Probably the wrong path or used the file extension or something
So then the enemy probably doesn't exist when that code's start is run.
Which is why you get the NullReferenceException
The argument is the name of the Resource that is located in the Resources folder, right ?
Yes but there are nuances to that. You'd have to show what you did in code and where the asset is exactly
Something like that "unitPrefab = Resources.Load<Unit>("Unit");" where "Unit" is the name of a prefab located within the Resources folder
i guess it does sorta solve the problem, unless you are going to disable a collider2d then its gonna mess things up i think
You're asking how to implement your solution without actually stating the problem you are trying to solve
no need to be an ass when someone asks for more clarification on why you can't do one thing, its part of the solution to know..
sure - assuming it's directly insude a Resources folder and has a Unity script on the root of the prefab and is named exactly Unit
If there's a reason you cannot serialize it, then that could affect other solutions as well
I am going to give you the benefit of the doubt here.
You are asking about an attempted solution to your problem, rather than your original problem. That is the essence of the XY problem. I linked to an explanation of the XY problem earlier.
The answer to your original problem may differ from the answer to the new problem you invented. Giving people context and explaining what you're trying to do could result in a better outcome.
We're not just asking because we like making people type.
Ha ok, I figured the difference out, I used Load("Unit") as Unit instead of Load<Unit>("Unit")
so rather than trying to solve problems for the goddamn riddler you could say what the situation is so that we can provide the actual solution
if you wanted OnTriggerExit2D to be sent to colliders you are intentionally disabling then you can just leave that as true and check manually whether the objects are destroyed/disabled in the scripts where you don't want it to react. or you can subscribe to the Application.quitting event to flip a bool and just check the value of the bool since the messages are sent after that event is fired
There are some situations in which you, indeed, cannot just drag a reference into a serialized field. Depending on the situation you're in, using Resources may be the best solution.
Not sure why they produce different results but they apparently do
It also might be a problem that you can solve much more effectively in another way. When you refuse to provide context, you are forfeiting those better outcomes (and leaving everyone wildly confused).
The version without the <Unit> returns the "main" object in the asset which is a GameObject, not a Unit, and GameObject as Unit returns null
wait you can disable it for specific colliders? i thought it was for all
no, which is why i gave solutions you can use for specific colliders
Hey! I've been having issues with NuGet, i cant install packages anymore, and it gives me this error:
Unable to retreive package list from http://.... System.Net.Webexception: The remote server returned an error: (400) bad request
I tried with different packages and it still doesnt work, tried reimporting the entire project, didnt solve anything, maybe someone here knows a good solution? :) I upgraded my project from 2019 to 2020, could that be the issue? Because it worked just fine before.
the "NuGet for Unity" package?
or is this something else
... damn, I really wasted that much time because I used a cast instead of Component check, well thanks again
You used the cast that fails silently too, rather than a normal cast. as simply returns null if the cast is invalid.
Uhh just the NuGet thing, theres a window for it in Unity when its imported. Just started using it so idk
which package are you trying to get?
newtonsoft.json
its already in package manager
Unable to retrieve package list from http://www.nuget.org/api/v2/FindPackagesById()?id='Newtonsoft.Json'&$orderby=Version asc&$filter=Version eq '13.0.3'
System.Net.WebException: The remote server returned an error: (400) Bad Request.
at System.Net.HttpWebRequest+<GetResponseFromData>d__240.MoveNext () [0x00152] in <5a2009c85b134970925993880e2ecb2e>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Net.HttpWebRequest.GetResponse () [0x00013] in <5a2009c85b134970925993880e2ecb2e>:0
at NugetForUnity.NugetHelper.RequestUrl (System.String url, System.String userName, System.String password, System.Nullable1[T] timeOut) [0x000b9] in <2dd456e09a61460fa915f49c38c2a123>:0 at NugetForUnity.NugetPackageSource.GetPackagesFromUrl (System.String url, System.String username, System.String password) [0x0006c] in <2dd456e09a61460fa915f49c38c2a123>:0 at NugetForUnity.NugetPackageSource.FindPackagesById (NugetForUnity.NugetPackageIdentifier package) [0x000ee] in <2dd456e09a61460fa915f49c38c2a123>:0 UnityEngine.Debug:LogErrorFormat (string,object[]) NugetForUnity.NugetPackageSource:FindPackagesById (NugetForUnity.NugetPackageIdentifier) NugetForUnity.NugetPackageSource:GetSpecificPackage (NugetForUnity.NugetPackageIdentifier) NugetForUnity.NugetHelper:GetOnlinePackage (NugetForUnity.NugetPackageIdentifier) NugetForUnity.NugetHelper:GetSpecificPackage (NugetForUnity.NugetPackageIdentifier) NugetForUnity.NugetHelper:InstallIdentifier (NugetForUnity.NugetPackageIdentifier,bool) NugetForUnity.NugetWindow:DrawPackage (NugetForUnity.NugetPackage,UnityEngine.GUIStyle,UnityEngine.GUIStyle) NugetForUnity.NugetWindow:DrawPackages (System.Collections.Generic.List1<NugetForUnity.NugetPackage>)
NugetForUnity.NugetWindow:DrawOnline ()
NugetForUnity.NugetWindow:OnGUI ()
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
oh its
big
oops
Ah, interesting.
"NuGet.V2.DeprecatedThe combination of parameters provided to this OData endpoint is no longer supported. Please refer to the following URL for more information about this deprecation: https://aka.ms/nuget/odata-deprecation"
Could not find Newtonsoft.Json 13.0.3 or greater.
UnityEngine.Debug:LogErrorFormat (string,object[])
NugetForUnity.NugetHelper:InstallIdentifier (NugetForUnity.NugetPackageIdentifier,bool)
NugetForUnity.NugetWindow:DrawPackage (NugetForUnity.NugetPackage,UnityEngine.GUIStyle,UnityEngine.GUIStyle)
NugetForUnity.NugetWindow:DrawPackages (System.Collections.Generic.List`1<NugetForUnity.NugetPackage>)
NugetForUnity.NugetWindow:DrawOnline ()
NugetForUnity.NugetWindow:OnGUI ()
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
also says this
https://docs.unity3d.com/Packages/com.unity.nuget.newtonsoft-json@latest
add package by name in PM
com.unity.nuget.newtonsoft-json
that deprecation happened a few years ago, so that's weird...
I would just go ahead and use the unity package.
could it be bc i changed unity versions?
So, I put an enemy object into the game off screen and that fixed the NRE. Now the question I have is how to I get the number from the enemy object shown on this screenshot to appear where the X (first_number within the math_generator) once my bullet destroys the enemy?
i didnt use physics2d much yet so i'm smoothbrain on that but ill try it. thanks for all the effort and telling me!
thank you! :) ill try this
wait i cant do "add package by name"
ah, you've got an old enough version of unity for that to not exist yet
Then you are only referencing that ONE off-screen enemy. But you are destroying a DIFFERENT enemy. That seems like a really bad solution. What is you goal here?
Is there a reason you're using such an old editor?
im using the Mixed reality toolkit,
Ah, so it needs an older editor. Gotchaj.
yup
The alternative is to just edit your manifest.json file. It's in Packages/.
and then put the thing you sent earlier?
"com.unity.nuget.newtonsoft-json": "3.2.1",
You would add this to the big list of packages. That ought to do it.
Hi all, I'm working on a project and my vs code editor stopped differentiating things like Vector3 and Quarternions. I didn't change my theme or anything, anyone know how I can make it look like the first photo again?
Sounds like it's not recognizing the .csproj files, and not analyzing your code properly.
You should follow the steps here: !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
If you aren't using the latest instructions, it might be flaky/randomly decide to no longer work
whenever I open up VS code, it registers like the first image for a split second then goes to the second.
this works! tysm :)
nice 👍
Json.NET is fantastic
The documentation is pretty good, so make sure you read some of that
ohh okay
hi i have a problem i have the navMesh component and everything is set like the enemy should chase but the enemy just dont move
As I mentioned earlier, the enemy_spawner object I have will generate clones of the enemy object. My goal is to transfer the randomized math_number variable from https://hastebin.com/share/kawocacuse.csharp to the starting_number text variable from https://gdl.space/imayoqavul.cpp and then do the same for the second_number text variable.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
yeah its my first time using this, since the project im in right now, i got it from a collegue and apparently it had SimpleJSON or something in it? someone said it was a Python library and said i could better use Json.NET, but ty for the help, ill read into it a little more.
I wouldn't say that's your goal. That is how you want to achieve your goal. As brought up to someone else earlier, this is what's called an XY Problem.
What is the purpose of transferring this number? Is this a math game where you have to solve answers to progress?
I missed part of the discussion, but if I understand it properly, what you can do is have a callback attached to every enemy_script. This callback is invoked whenever the enemy is destroyed and tells the math_generator that a "number" was destroyed
I have a cube with two child objects. Is it possible to get which way the green arrows rotate by script?
That would be transform.up
what you mean? those are up, right, forward arrows
Red - X - right
Green - Y - up
Blue - Z - forward
transform.up will be the direction your transform's green arrow points
i have tried to print the position.y and transform.up but both prints the same value
thats why i was wondering
well, position.y is a float
and transform.up is a vector3
so I would not expect for them to be the same value!
They should be different but they are the same?
hi i have a problem i have the navMesh component and everything is set like the enemy should chase but the enemy just dont move
transform.position.y is giving you a value of 5.2
how would you Parse something with newtonsoft? bc my old code just has JSON.Parse, but that wasnt with newtonsoft.json
Show your code.
@swift crag Should the two object not have different orientations?
there are several ways. JsonConverter is one. JObject is another.
You'll use JsonConverter's methods.
They should, yes. So I'll need to see the code you're running.
Kinda feels like you're just accessing the parent object's transform here?
@swift crag
Okay, that looks fine.
RegisterLaser is in the parrent script

