#💻┃code-beginner
1 messages · Page 356 of 1
this declares a get-only property
neat
public int CoolInteger
{
get
{
return otherObject.myInteger;
}
}
this is the most verbose way to write that
=> is used in several places to use an expression instead of a whole block statement
public int GiveMeThree() => 3;
for example
public int CoolInteger
{
get => otherObject.myInteger;
}
another example
Huh, cool. Thanks!
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties
if you've never used properties before
I've done this once when writing "features" for a component that all care about a few values from the component
just to make it less verbose
still kinda iffy on it
😮
cursed? public bool IsSpacebarHeld => Input.GetKey(KeyCode.Space);
very reasonable
oh, I mean my specific use-case of saving a bit of typing
I use => everywhere
I have an object with a collider and OnTriggerEnter2D. it's working all good. But the OnTriggerEnter2D is being called when I enter the trigger of a different object? Anyone ever experienced this?
The triggers overlap eachother but they're on different objects?
public int TheInt => myObj.itsInt;
vs. just using myObj.itsInt directly
yes, that's how it works
But surely OnTriggerEnter2D should only work for the object that the script is attached to?
it works when the object is attached to is involved in a trigger intersection, yes. With any other object.
Sorry for bothering again, but do I put this script inside the main camera?
I don't know what you mean by this. It fires whenever a trigger collider on the same object as your MonoBehaviour hits another trigger or collider
It could go anywhere
it would make sense to be on the camera, I guess
I have 2 trigger colliders. One Big, and one small. The small one is inside the big one. I have an OnTriggerExit2D on the small collider. If I exit the small collider, it called the OnTriggerExit2D for the small collider, but it also does it for the big collider, despite me still being inside it
OnTrigger functions are run on the rigidbody that the colliders are attached to. If a Rigidbody contains multiple colliders, that code will run whenever any of its child colliders has an exit event
The 2 trigger colliders are on 2 seperate objects
Do they share a parent object
Oh yeah
how 2 make some field editable on runtime in editor?
public or [SerializeField]
Would it make sense to put a full 2d game on a canvas? I've read online that the canvas updates every time one object updates.
hello, is this where i could ask for help with code?
Here
No
i have this problem where if i have more than one coin in the scene, none of them load except one
What do you mean by "load"? Like, you put coins in the scene, start the game, and all but one are destroyed?
yeah
Show !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.
using UnityEngine;
using UnityEngine.UI; // Import Unity's UI library
public class Coin : MonoBehaviour
{
public int coinValue = 1; // The value of the coin, can be set in the Inspector
public Text scoreText; // Reference to the UI text element
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
CoinDisplay.Instance.AddCoins(coinValue); // Add the coin value to the coin display
UpdateScoreText(); // Update the score text
Destroy(gameObject); // Destroy the coin object
}
}
void UpdateScoreText()
{
if (scoreText != null)
{
CoinDisplay.Instance.UpdateScoreText(); // Call a method to update the score text
}
}
}
using UnityEngine;
using UnityEngine.UI;
public class CoinDisplay : MonoBehaviour
{
public static CoinDisplay Instance; // Singleton instance
public int score = 0; // Current score
public Text scoreText; // Reference to the UI text element
void Awake()
{
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad(gameObject); // Don't destroy this object when loading a new scene
}
else
{
Destroy(gameObject);
}
}
public void AddCoins(int value)
{
score += value; // Increase score by the coin value
}
public void UpdateScoreText()
{
if (scoreText != null)
{
scoreText.text = "Coins: " + score.ToString(); // Update the UI text with the current score
}
}
}
Did you put CoinDisplay on the coin objects
yeah
So, it's doing exactly what you told it to do
Since CoinDisplay is a singleton, it's destroying every additional copy of it
so there is only ever one
Doesn't really matter where it is as long as there's only ever one of it
okay thank you
If you put the changing objects on their own canvases it's not so bad, assuming you don't have much changing. Like a simple puzzle game. Definitely don't do it if there's a lot moving and changing/
But there's probably other ways to do what you need
ok, how 2 make it with static field?
Static can't be displayed in the inspector, unfortunately
any crutches?
A separate var on the class to expose it, which on Awake is made equal to the static.
Then in OnValidate you copy the separate var to the static, so it changes the static if you modify it?
Its hacky, but might work
i just tried public var i => staticvar; & throught get; set;
you don't
var cannot be serialized
You cannot simply write public var
it's just any type, i have float
Alright
properties won't show up in the inspector either, so this won't get it to show up unfortunately
If you wan to serialize a property, you have to make sure it doesn't have a custom getter or setter
Ah, true, but in this case they'd need one so that it modifies the static
// works
[field: SerializeField]
public Something MyProperty { get; set; }
// doesn't work
[SerializeField]
public Something MyProperty { get; set; }
// doesn't work
[field: SerializeField]
public Something MyProperty => _something;
today I learned
thx
stop, it doesn't work
[SerializeField] private Something _myField;
public static Something myField;
private void OnValidate()
{
myField = _myField;
}
That's with the static
static things don't show up in the inspector no matter what you put before them because they don't belong to an instance. It wouldn't make sense to have them editable through an instance
The code I've shown works unless you're trying to use the variable of type Something, which you probably don't have, or making the property static
thx
Also first consider whether you do need this static variable
Cause I'm not sure
If you really do need to serialize it this way, why not forget about the static one?
Sounds like they want a global value for all instances to use?
But still control it in the inspector during play?
I don't think there is a need for both static and serialized variables. It should be better to just remove the static one
This way they can simply make all their serialized variables static, which will definitely reduce the readability
any ideas how to make text ui to hide when gameisoverui shows?
Have whatever turns on your gameisoverui also turn off the object/canvas/etc that contains the UI you don't want
but to make sure- loading from text wont cause any loss in quality right? i feel like mp3 -> audioclip conversion might generate much more samples that it has when compressed
the same way you hide any other game objects
you should start getting into a habit into googling things
I don't see your original message, but regardless of what format you import with - Unity will compress and convert it to a format for your target platform based on your settings. So if you override it as uncompressed, and load in mp3s, yes it will make it bigger. If you add raw wav files, but let it compress by default, it will compress them. What you put in, and what format and compression it uses for the platform, is separate.
Unless, of course, you are doing something like live-streaming in the data and bypassing the importer/exporter.
OK, you said mp3 -> audoclip though. That will end with a unity asset conversion.
It will not generate new samples.
okay so it just me messing up byte conversion then
Hopefully this is the right channel. I'm working off a tutorial template and need to fully rename the project.
Folder is named right, and it generates the .sln file correctly.
The .unityPackage still has the old name. I did change the name in Project Settings > Player but I haven't seen that have any effect yet.
If I change the namespace in Visual Studio, everything breaks so that must not be the right track. But I do need that namespace changed as well.
Where else do I need to change this name?
unitypackage is just a package u import.. the name really doesn't matter
the folder name is teh projects name.. once u open the project u can go into project settings and make sure hte name matches
I did change the name on this page, no effect
it doesn't really have an effect until u build the game.. that becomes the exe name
Yeah I saw that the build files are updated now, my bad
Project name can be anything really, I always just give mine generic names like "Turn based RPG" and then I change the product name in settings when I know the final game's name
So the Unitypackage file, am I able to just rename that in Windows Explorer without issue?
I already know the name I want 🤷♂️ Why are you guys trying to talk me out of this lol
we're not.. ur misundertanding.. the unitypackage is the package u import..
liike a zip file..
its name also doesnt matter..
yeah that unitypackage file is not part of your project
its an extra file thrown in there.. like if u didn't want to open abrand new project.. u could import into an existing project
and again its name doens matter because the files inside of it.. are named what they're named and are gonna import the same no matter what u name it
So, a yes to this question then?
yes. name it whatever you want.. its been answered
No, not directly lol
Thanks
That's a direct answer if I fully understand the context of how to work with unity, but I lack that context. That's why I needed a yes or a no. Thank you.
As for the default namespace, what do I need to do to safely change that?
Change the default namespace!?
Where do I change that? I changed the namespace in VS but it broke everything
First explain what you mean by that. It makes no sense
Maybe I am missing some context
But you cannot change the default namespace
Damn I'm feeling a really hostile vibe in here. Why are people getting snarky about beginner questions in #💻┃code-beginner ?
You can rename a namespace in VS through solution explorer
hte namespace u can rename thru ur editor
Who is snarky? I don't see any of that
Ah, so not the default namespace. The namespace of the package?
u can rename ur namespace using the rename.. now if ur ide isnt correct configured that may not change it everywher.e.
Or possible by right clicking on the namespace in your code and choosing rename
and u'll have to manually change it around the project
Spawn beat me to it
i had to test myself first lol.. wasn't sure VSCode would rename them all..
but it does 👍
When I do F2 to change this project-wide, the project stops working. Project Settings doesn't open.
indeed
Just to explain my confusion. default namespace is the namespace that is there by default when you don't write any namespace
And you cannot change that
But I see I WAS missing context
Ok, I'm going off what VS calls it, the one it will enter into files automatically.
I checked if there was a mismatch in .csproj but no references to the name at all in there
RoqueSharpTutorial is the main namespace..
.Controller means theres a class called Controller within that namespace somewhere.
your renamed would be SomethingElse.Controller
Correct
can't remove that .Controller bit unless u rename it as well
Given that VS is configured and the project is loaded, hitting Ctrl + R twice while the caret is over the namespace name will trigger a project-wide rename operation
try 
I'm trying to rename the RogueSharpTutorial portion, not the latter part
try what spr2 mentioned.. im working out of VSCode at the moment
I did try this earlier, the project stopped working in unity after I tried it
Stopped working as in, you got errors? Scripts detached from game objects?
No, it loads the game but none of the sprites from the look of it
Canvases are intact
No sound to check
Changing that namespace back causes it to work again
So I think there is still a mismatch somewhere
Unless the sprites are loaded from the code, it's unrelated to the code
Console might be full of warnings about monobehaviours being missing
not a limbo master
What daily yoga does to a mfer
that looked painful
"Look up"
SNAP
"... ow."
no like logically speaking
57 million long byte array
meaning takes up around 57 megabytes
going below that would reduce audio quality isnt it
how is audio file itself much smaller then
I have no idea. Where is the 57 mil coming from?
i debug logged the samples in untiy
57 million bytes, 14 million floats
mp3 is some kind of zip isnt it
In the broadest sense that they are both formats and deal with compression... i guess so
In any real sense, no, not at all
that why i was getting huge white noise when going for mp3 itself
because it was compressed and unusable
so i need in fact convert it to raw audio
Once it is compressed into an mp3, the data is lost (which is why it is called a lossy format)
Converting it to "raw" audio (not really a thing, but I get what you mean) will either do nothing, or make it worse
Yes.....
Not sure what that has to do with what I said.
Compressed files are indeed smaller
oh dear god, please don't try and encode a 60 megabyte file to base64 just to download it as a string like i just know you want to
again, why do you need to do all of this. you know you can just download the audio file directly from the server, right? you don't need to convert it to a string, send it to the client, then convert it back
and all of this is still illegal no matter how you try and go about it because you do not have the rights to distribute these songs
what you are trying to do is actual piracy
its not about songs or whatever
Oh damn. Did not realize the context.
Alright, I'm out
which is pretty fucking wild considering you don't need to do that at all
Generally speaking, transmitting stuff over network is done using a stream of bytes. Of course you can interpret these bytes as characters, but why?
i already succeeded at that
the issue im seeing is i should take dirty work in my hands with changing formats
and i can succeed at flinging my shit at unsuspecting zoo goers, that doesn't mean i should or that it is in any way a good idea
you don't need to do all this reencoding just to download files as strings when unity already comes with tools to download files very easily at runtime
I will just say, again, if it is mp3, do not try converting it to pcm. That makes no sense. It has already been dithered and the data is already lost
whats the use of mp3 bytes for audioclip creating
they are unusable
need be turned into something else
If you don't know the format of what you're getting from the server, why not write it to a file and put it through an online recognizer? There are plenty of services which can guess the file type based on their contents
its my server so i can control format
That is a separate issue that has nothing to do with them being mp3
(Meant to reply to the "they are unusable" part)
just everything else than pcm has not worked
wav semi worked but i heard some noise in background already
did you debug ? if so how
for example would start with
LevelManager.GetInstance().currentLevel putting that into a variable
debug it
never assume your values are what you think they are
it says timer added
but in other scenes like level 1 level 2 the text updates
but in level 3 it doesn't
so just text doesn't change? but the value adds?
How are you loading the data? Tried with UnityWebRequestMultimedia.GetAudioClip() and passing the expected format? You can even enable streaming if the file is large
See https://forum.unity.com/threads/async-streaming-audio-with-unitywebrequest.487062/ for an example
be careful with this
timerScript = FindObjectOfType<TimerScript>();
this will find the First one it can,
make sure you dont have 2
2 these?
audioclip.create and only that
mhm
since this is going ontimerScript.timer.ToString
but in other scenes it works in the level 3 scene it doesn't 🤔
thats why i said to check if you dont have an extra TimerScript left over somewhere in scene3?
also debug.log your currentLevel
i only have in level manager and in obstacle but one is marked other is not
i tried debbuging it it says Added 5 seconds for level 3
where did you put log
alr
can you show me during playmode in level 3 the ObstacleController object
me bad i thought u asked video
nah just need to see during playmode which component it has
that doesn't answer the question lol
u know if u disable that script.. it can't re-enable itself..
Do you want ObstacleController to get TimerScript from Obstacle?
yes
im suprised ur still working on this 😄
ahh okay
that makes no sense. wdym thought you said the one from Level Manager
why would you want Timer from the Obstacle
why is it still there in the first place
You dont need 2 timer scripts..
but one script is for level manager
in level manager GO its enabled
so what?
so i don't think that would work without it
alr i will disable it
u saying that im grabbing the one that is disabled
yes.
thats what FindObjectOfType does
it literally finds the object of type
it doesn't care if its disabled or not
it does have a bool you can pass for that to disable
ok
to recap, You're not grabbing the one that is useful to you LevelManager timer script
you're grabbing the one on obstacle that is disabled, hence why the text isn't changing
because value isn't updating on correct script
You should not even have the one on Obstacle was my point from before
you could..sure..or just delete the extra copy.
again, why do you need 2 Timer scripts?
why are you showing me this?
i can delete the other one
why
if its disabled why is it even there ?
you still have not answered that
i wasn't focused on that problem so i didn't do anything to the script i fixed it
should i use DieID = Animator.StringToHash("die"); then set bool or the .setbool("die") for string lookups?
using the hash is more efficient over a long period of time (assuming you store it in a field and don't just hash it each time). if you just need set it once or twice though using the string directly is perfectly fine
that literally was the root of problem though lol why would you not focus on that
do you ever have an epiphany and suddenly realize that you can turn 30 lines of code into 5?
what a great feeling
lol
then you realized maybe you shouldn't have shaved off that vector normalization
And those 5 lines can be turned into 1 with linq, which you won't be able to read when refactoring the code anyway
And that one line can become zero when you decide to just lay face down on the floor and dream your game into existence
Trying to open a UnityPackage, and the launcher just spins endlessly. How do I troubleshoot this?
God damn it, just click it a bunch of times? Why the hell did that work
nah when i was a beginner they were all bulying me cause i didnt know how to round with code
guys which better to detect the attack from an object is it by using polygon collider or a raycast?
No you were bullied because we kept sending you the documentation for Mathf.Round and you just wouldn't click on it
yeah but some people dmed me and told me to give up on coding
namespace Phone
{
using Player;
using UnityEngine;
public class PhoneAnimation : MonoBehaviour
{
public Transform phone;
public Transform camera;
public float rotationSpeed = 5.0f;
private Quaternion originalRotation;
private Quaternion targetRotation;
private bool isRotatingToPhone = false;
private bool isRotatingBack = false;
private float transitionProgress = 0.0f;
private bool toggled = false;
void Start()
{
targetRotation = Quaternion.LookRotation(phone.position - transform.position);
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Q) && !isRotatingToPhone && !isRotatingBack)
{
toggle();
}
if (isRotatingToPhone)
{
camera.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
if (Quaternion.Angle(transform.rotation, targetRotation) < 0.1f)
{
isRotatingToPhone = false;
}
}
if (isRotatingBack)
{
camera.rotation = Quaternion.RotateTowards(transform.rotation, originalRotation, rotationSpeed * Time.deltaTime);
if (Quaternion.Angle(transform.rotation, originalRotation) < 0.1f)
{
isRotatingBack = false;
phone.gameObject.SetActive(false);
}
}
}
void toggle()
{
if (toggled)
{
PlayerController.instance.toggleMovement();
isRotatingBack = true;
toggled = false;
} else {
PlayerController.instance.toggleMovement();
phone.gameObject.SetActive(true);
originalRotation = camera.rotation;
isRotatingToPhone = true;
toggled = true;
}
}
}
}```
Does anyone know why whenever i press Q it just locks forward and doesnt let me unforward
hello i need help with something, im coding for a school project and decided to make kind of a horror game and im stuck, i want to when my player and my"monster" collides ther pop ups an image, i dont get it to work please:D
What part do you not know how to do, the collision or the pop-up
@polar acornthx ill take a peek
Report the ones that dm'd you to the mods.
But that is not a reason to say everyone was bullying you. That is an objective lie, and I think it is not ok. The people who were talking to you HERE were not bullying. I was there and remember that
nah not everyone but i was getting bullied
yeah ofc if they wouldnt bully me here they would get muted but in dms not really
As I said. Report them. But stop all this here
YES SIR YES SIR 🫡
you can mute dms per server too so opt into that setting
ehm im really sorry to bother again but i dont understand anything, lets just say im super mega new to coding but i really enjoy learningXD
"since ur the one that helped me the most... do mind just doing my entire project for me!?
i did not know that either . . .. . .. . .
If you know how to detect the collision, and you have an object you want to enable, you just call SetActive on that object
I have a sphere gameobject, the X and Z axis are locked, so I can only move the gameobject up and down on the Y. A script is attached to the gameobject that allows me to click and drag it up and down.
The problem is when I hold the gameobject and move far or closer, the gameobject moves a lot faster and not the speed of the player looking up and down. I understand the issue is the X and Z axis being locked is causing this, but I’m having a hard time finding a way to fix it without unlocking them.
the z and x axis constraints are not in code but on the gameobject itself with a component called, " position constraint"
ur the OP
how to make with playerwalksound when gameisover the script must disable??
should i SetActive the name of the image?
no more annoying red pills popping up everywhere'
here is the code on the game object
You should call SetActive on the object you want to set active
Could you consider rephrasing that question in a way that makes sense
how to make it so my player doesn't make walking-around (footstep) sounds after the game has ended
lol.. feels like price is right..
yes
heres a video for better understanding. Im not really holding it but trying to move it on the y axis
you could set teh footstep script to be disabled.. in the gameover script.. (using a reference to the script)
So, you have an object that can only move up and down, and you want it to move at the player's aiming speed, but it's moving at a constant rate, no matter the distance. Am I understanding this correct?
Ah, the video explained it. Seems like what I expected
So you wanna put the distance between your player and that ball in count?
okey ima try
Sound like you could utilize raycast to the plane
What you could do, instead of having the aiming input move the ball directly, consider doing a Plane.Raycast to get the point a ray from the camera intersects, and set the ball to that position:
https://docs.unity3d.com/ScriptReference/Plane.Raycast.html
You'd make a plane at the ball's XZ, and get the ray from the center of the camera
just use a [SerializeField] private FootStepScript footSteps; and u can drag in the gameobject / the scripts on
Then, get the plane intersect point, ignore the X component, and set the ball to that Y position
then its just footSteps.enabled = false;
or footSteps.gameObject.SetActive(false); to disable the entire gameobject
hi i know it is probably a stupid question but i have looked around and can't find anything to match what i need to do. Is there a way to transfer the information from a variable in a different "void" ,don't know what to call it, as i am having a problem where it wont unfreeze a rigidbody's position as it doesn't know what it is.
i tried it doesn't work https://hastebin.com/share/ozixabibip.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
It's called function/method not void
Show the code and what the issue is
"a void" is a return value of a method
void means the Method doesn't return a value.
it's a method, not a "void". and you can either pass the object as a parameter to the method or store it in a class-level variable
what doesn't work
the sound doesn't turn off i dragged in the gameobject
// Check if the player is below the ground
if (transform.position.y < -10)
{
isDead = true;
gameManager.gameOver();
footSteps.enabled = false; // Disable foot steps when game is over
}```
this should disable it..
That being said you probably should start from beginner C# stuffs pinned in this channel, no use trying to figure out without basic knowledge
Try logging footSteps after you disable it and see if that code runs
Don’t completely know who to reply to here but, thanks for the proper term. Can you explain how I can pass the parameter to the method?
did u check the inspector after the code should have run
the tickbox next to hte component should become unticked
there are beginner c# courses pinned in this channel. start there if you don't even know how to write a method with parameters
Thanks didn’t see the message from someone else earlier
float c;
public void CombineToMakeC(int a, int b){
c = a + b;
}```
CombineToMakeC(1,2);
it says they disabled
ya, check the gameobject and see if the tickbox next to the component is ticked or unticked
whats good with those speed lol
;Dd
someone doing Rigidbody * time.deltaTime?
Okay, so the object you have assigned to footSteps is being disabled
yes it does say that
Why do you have two variables pointing to the same object
I have no idea how that is an answer to my question. Why two variables that hold the same reference?
yea, thats odd.. if u already had one.. there wasn't a need to create another one..
i dont see how thats possible.. unless something else is enabling it
you could just mute the audiosource
how?
all its functions and parameters are down below..
audioSourceReference.mute = true;
or audioSourceReference.Stop();
and before u go gungho with it.. audioSourceReference is just an example name.. and u use w/e u want to call urs..
as long as it has a reference like any other type
umm.. idk what to do here
wat
Transforms are attached to gameobjects
you can't create one without the other
those are separate things
i'd just create a transform within the gameobject and use what u need from it
make a custom struct
u can unattach it when the game starts
orrr custom structs work too
just more typing..
i use a transform for a car controller i have.. the transform follows the rigidbody but can't be parented to it..
so the script just references it.. and i unattach it at start
mockTransform.parent = null;
mockTransform.transform.forward i see what ur doing there
i do that too.. i call them mimics
lol
yeap.. just use u an extra gameobject for its transform
and call it a day
Hey everyone can someone help please, i want my character to jump but he don't jump
oh jesus
!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.
also !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
clean ur monitor bro
How ?
with windex probably
haha microsoft using github to show other peoples code
😄 lmao just messing.. but for real.. post code using an external paste bin site or something
ik its just funny , when you agree to a free* account
I started unity 5 days ago i m a beginner i just want my character to jump, how ?
If you want help on this server you obey the rules of the server. you have been shown how to post code
Ok thx
tf is going on here??
just the 1
unless VSCode is trolling me in the background
i renamed the symbol yesterday and all was fine..
today i got all those errors.. which all i had to do was modify a character or so and resave
and they get fixed
¯_(ツ)_/¯
its unity6 soo i guess ill give it a pass
If you don't make your own constructors, by default the class will already have a parameterless constructor accessible.
Do not implement constructor on classes deriving from MonoBehaviour. As Unity manages the lifetime of the objects, constructors might be called at unpredicatable times, or not called at all.
Do not call constructors on classes deriving from MonoBehaviour, they won't be attached to a GameObject and it's not valid, use AddComponent<T>() instead
creating GameObject is okay just not MB
Unity handles MB for you , so you use Awake as faux constructor (to setup object)

am i missing something?
wouldn't it just be cs GameObject newGameObject = new GameObject("MyGameObject"); Transform newTransform = newGameObject.transform;
how can i change a String to a Float?
i know that i can easily change a float/int/double to a string using .toString() but there isnt a toFloat Maybe ToInt32 b
tysm,
Yup, that works
yay! 😄 lol
is default spawned at Vector3.zero worldpos?
exporting unity build for android, and it keeps giving me gradle failure, do you guys know how to solve this?
i messed around for a bit and understand what you're saying and plane.raycast but implementing it is a bit difficult for me. I feel I may need a whole new method of moving the object to begin with
For new GameObject? Yup, transform will be all default values, so 0,0,0
https://gdl.space/obepoxumel.cs
this is what I have connected to the object for me to move it. Do you think I can do it with what I have or need a whole new method
if it works ur fine
i usually move it in update and just use a bool in the OnMousedown/up
are you responding to me?
Are animations in canvas ui expensive?
The entire canvas is redrawn each frame, so it can get heavy if there are a lot of objects under that canvas.
Animations can cause layouts to get recalculated every frame
To add to SPR2's comment, its best to put your animating thing on its own canvas, so that you minimize what is redrawn to just what is actually moving
Or use a tweening library which doesn't use the animator system.
Before changing things though, make sure you have used the profiler and confirmed there's an issue caused by excessive canvas renders
would using the animation system actually matter?
it's just setting properties on things
I guess it can wind up setting lots of properties on lots of things, constantly
Not if you only keyframe the stuff you plan on changing
I have my own fancy layout group classes that I use to "animate" UI elements from time to time, and haven't noticed any performance hit when using them. But when I'm doing that there's only UI being rendered and nothing else is going on. I'm not simultaneously rendering a 3D scene under my fancy moving UI.
right -- i just don't see how this would make a tweening library "better" here, then
I don't have much UI animation beyond fading canvas group alpha, but I do have a lot of menus. I deactivate whatever isn't being used and it runs very well.
I did used to have a problem where I deactivated the entire menu when its alpha hit zero...but I was using SmoothDamp to change the alpha
0.0000000001 > 0
Faster customization of easings, predefined effects, ability to chain them or run them at the same time
Depends on if you prefer doing it all via code, or with curves
i vastly prefer code-driven behavior
yea
how can i get the Volume Variable to be the same as the slider value
ive tried some stuff like Slider.value = float; but that just makes the Slider unusable
The slider has a value of 0 to 1, so you need to lerp it to the range you want through some other script
the value is 0 to 100, i checked the min value is 0 whilst the max is 100
it only works when i change the volume variable thru the inspector
the issue im having is creating a planeraycast on an object in which the script is assigned to that object to move. How can I make a plane at the objects XZ axis if that same object is whats holding my script to move using ScreenToWorldPoint. I think I may need a new method to move the object, but this is the only way I know I can move it without holding the actual object
Have you googled how to do this? There are tons of tutorials out there.
For volume you really dont want to just assign the value from 0 to 100 either, youd want to use a common formula you'll find in most tutorials which is representative of how we hear sound
Is your slider's On Value Changed doing something?
i have already but they all used the same thing
public method(float name123)
then for me to put it in the OnValueChange
but then i cant get the name123 variable to be the same as my volume variable as Volume = name123 just makes the slider uninteractable
So, its getting late, my head is stuck 😄 Does anyone have a quick hint on how to achieve the following. I got a hand and head position, I want to target the UI to stick with the hand (working) and look at the head (working). What I am missing now is, how do I add some kind of offset to the final position in relation to the angle?
Vector3.Lerp(
uiRuntime.transform.position,
XRHandPalm.instance.transform.position + offset,
Time.deltaTime * RuntimeHandler.Settings.uiFollowEasing
);
would be easier to answer knowing the usecase of what the mechanic you're going for here
ye but i cant make it so the variable that i have to make has the same value as the variable i want
Show the code for that method that OnValueChanged is calling
like i have this public void ValueChange(float volume) { Volume = volume; } then the slider is usuable agian but then the Volume Variable deosnt change
its confusing but if u look at the first letter of those variables one is capitalized and one isnt
making them 2 different variables
Is anything in your SettingsManager forcing the slider's value to be something? Like in Update?
nope
i dont even have a update method
And if you remove SettingsManager, does your slider move again?
And make sure that from the slider you have selected your method under the "Dynamic Float" section, so the new value is actually passed to your method, not some constant.
its only when i say smth like
Volume = VolumeBar.value;
or
Volume = volume;
i have no idea what a dynamic float is as the tutorial said nothing of it
It's an option that appears when you select the method to call on the event
In the Inspector
ye
So how would you add lets say 0.5 to the right inside my code snippet?
Maybe you have check the "Whole number" thing on your slider by error or something and you are trying to obtain a float, idk. A slider isn't that hard to use
Can you show the code for your Volume = VolumeBar.value;, ?
I have a sphere gameobject, the X and Z axis are locked, so I can only move the gameobject up and down on the Y. A script is attached to the gameobject that allows me to click and drag it up and down.
the z and x axis constraints are not in code but on the gameobject itself with a component called, " position constraint"
The problem is when I hold the gameobject and move far or closer, the gameobject moves a lot faster and not the speed of the player looking up and down. I understand the issue is the X and Z axis being locked is causing this, but I’m having a hard time finding a way to fix it without unlocking them.
I was told using planeraycast to make a plane at the ball's XZ and get the ray from the center of the camera. The problem now is the way I'm really moving the object. https://gdl.space/obepoxumel.cs .. Since im doing it from the object itself and not the player, this is where I get confused cause I can't find another way to move the ball like I am now or implement the planeraycast with what I have now.
i think i fixed it i just turned on the Handle Slide Area
yeah it isnt but im considered to be slow
here the vid that might help you understand better what im doing
I'm trying to build a splitscreen system from scratch. I'm using the joining feature of the player input system to get events. And on join i'm firing this:
void DoSplitScreen(PlayerInput playerID)
{
Debug.Log("Initializing SplitScreen for player: "+ playerID.playerIndex);
var camera = playerID.camera;
float cameraXMin = playerID.playerIndex / 2;
Debug.Log("CameraXMin equals: " + cameraXMin + "since playerID is: "+ playerID.playerIndex);
float cameraYMin = 0;
float cameraxMax = cameraXMin + 0.5f;
Debug.Log("CameraXMax equals: " + cameraxMax + "since playerID is: " + playerID.playerIndex);
float camerayMax = 1;
camera.rect = new Rect
{
xMin = cameraXMin,
yMin = cameraYMin,
xMax = cameraxMax,
yMax = camerayMax
};
Debug.Log("xMin: "+ camera.rect.xMin+ " xMax: "+ camera.rect.xMax+ " yMin: " + camera.rect.yMin+ " yMax: " + camera.rect.yMax);
}
it should work, yet the result is always the same. It looks like cameraxMax = cameraXMin + 0.5 is referencing the previous cameraXMin. Why?
oh so the offset gets messed up?
And what if there is no parent? I guess I need something like
UIRuntime.transform.position += UIRuntime.transform.TransformDirection(RuntimeHandler.Settings.uiHandOffset);
Yeah no, that code did not work either. Jesus, its such a simple task but I might just need some sleep 😄
I believe so, all I want is the speed in which the ball moves up and down to match my speed of the camera while im holding it.
Even when I move closer or far away
can someone help me fix this
what exactly -
Hello again everyone. So i managed to do some stuff by myself but i ran into an issue rn. Player should die when slime touchs it and indeed it dies no problem here but i didn't managed to add die animation. I mean there is a die animation but there is no time to play it, player just disappear. ho can i manage to do that. this is the code:
Player script:
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Enemy")
{
anim.SetBool("is_alive", false);
gameObject.SetActive(false);
}
}```
using a plane projection is prob the best way for sure with a ray
the errors
Configure your !ide so you don't make spelling errors
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 is configured
here we go again..
It very demonstrably is not
huh
I told you this yesterday and you still haven't done it 🤔
Miscellaneous files - not configured
Unity classes such as MonoBehaviour uncolored - not configured
Line with error on it not underlined - not configured
you wrote serializefeild
Do you think I can implement this with the way im doing it? Or will I need to find another way to move the object with a new method
Follow the guide
No it is not
lets see difference between yours and mine @pure pike
ok
That looks quite promising, let me try and thanks 🙂
personally I would use the plane method
if you want an example I can show you when I get back home soon
should be easy though look at docs for plane
the is ScreenToRay too you can use directly then put that on the plane for obect placement
other than well fixing your editor, try and learn how to read the error messages: they give you the exact line where the mistake is so you can find it easily. as an example in your screenshot your error says "...playerMovement.cs(18,5) this is the file and the line that is causing the error
I haven't test to much with that but It looks that for 3D you have to use Raycast and maybe a plane. I have see this video: https://www.youtube.com/watch?v=0jTPKz3ga4w
So maybe something like this can work: https://hatebin.com/jqeyurtfdf
🌍 Get my Complete Courses! ✅ https://unitycodemonkey.com/courses
👍 Learn to make awesome games step-by-step from start to finish.
🎮 Get my Steam Games https://unitycodemonkey.com/gamebundle
💬 One of the comments I get a lot is people asking why the code shown in the video isn't working, and usually the reason is because in the video I showcase ...
i know that
oh god his videos are the worst..
It is imperative that you do not simply fix this one error and go about your business. Configure your IDE so you stop making spelling mistakes in the first place
cmon why
You see I thought that, but there are worse
i sorta know how to read errors
Should I give that watch or would it make this more confusing?
i thought he was really knowledgeable, what's wrong with him?
aside from the older ones using the annoying "use my library to use this method" and downloading from his site.
His other videos' now are watch this other video before you watch this video. which is quite annoying
Ill watch wen I get home
I keep a counter of the times that people claim they have exactly the same code as the tutorial:
"I did it exactly like the tutorial so why does theirs work and mine doesn't" counter:
Number of times it wasn't exactly like the tutorial: 162
Number of times it was exactly like the tutorial: 5
Number of times the code literally did not exist: 1
2022-07-19 to 2024-5-21
Three of the five "times it was like the tutorial" and the one "time the code literally did not exist" were all Code Monkey
that is true 
but most dont claim to be writing "clean code"
which is what tickles my gooch
i did everything in the screenshots and its still not configured
Thanks again, this seems to be working. Jesus, now seeing it it totally makes sense. Thanks for saving me some hours of sleep 😄
no idea if that even covers what you need
Trolin, ill check out the vids ina bit tho. Appreciate the respond
oh man XD
@polar acorn ^
I have no idea what im doing but ill figure it out
i just thought i was too dumb and messing stuff up
There's more than screenshots. Did you go through all the words too
did you install VS through the hub or manually
manually
if you still cant figure out Ill send an example with a plane when I get back in 20 min or so
Show a screenshot of your VS Workloads section where the Unity workload is installed
is there something I'm not understanding?
i changed it to the vs thing bc i was on open by extension but i swear i changed it to vs but ig not
close vs, click Regen and open script again
https://hatebin.com/dipkrzqfns
i have a god camera that uses the plane technique
i got it now yippie
honestly i have this annoying bug that it'll reset this option each time i restart unity. check out for it
Well, you have also this tutotial that can clarify some ideas, but if you blink you lose it: https://www.youtube.com/watch?v=mF_BB_YsyDk
But the summary is, for 3D you have to use Ray
This is how to you make an object follow and rotate around the mouse in Unity in 62 seconds.
oh that stinks
iirc it should help if next time it happens you manually look for visual studio's executable and select that
@faint agate
but obv you want a diff normal dir, prob maybe transform.forward
theres nothing wrong but it still says theres an error
im not tho
https://www.youtube.com/watch?v=rnqF6S7PfFA&t=496s&ab_channel=GameDevGuide @faint agate i used this tutorial.. he's the one that exposed me to using the raycast plane method for moving
huh
LoL
i get it now, i got it so thanks
; is like a period to a sentence
i know
You are. Remember, a line only ends when it hits a semicolon. So, line 18 is actually private float jumpBufferCounter [SerializeField] private Rigidbody2D rb; which makes no sense
i got it now
those dang semicolons
the importance of IDE config ✊
python users got so scared of them they took em out 
im soo glad i dont have to use python very often
yeah its a little weird to setup but when it is MY GOD ITS SO GOOD
you got lucky lol usually there are some people here who have to do the whole Reload with Dependencies on the assembly inside VS
i made a video on how to configure it.. and because of that i had to unconfigure and reconfigure it multiple times..
some of those times required me to do a restart on the ide and my pc
glad thats over with 😄
sometimes it says the assembly is incomplete or missing
😢 VSCode before Unity plugin came out was the WORST
Visual Studio mac was the easiest
only used rider for a year was also pretty easy, nothing to setup
💯 , thank God for this
Microsoft really came in with the clutch
Unity would've took another 5 years
they figured out how to connect VSCode to the Visual Studio package 😛
Frienemies
yeah the new version dont even install the VSCode package anymore lol
that shite goneee
ya, the new package manager doesn't even let it exist hehe
hey sry to bother, I got an issue understanding instances, i'm using a "Spawner" gameobject with a script linked to it and I would like to copy this object and maybe use it with a spawnRate not set to 5 but to 20 for exemple, therefore I would have one "Spawner" object with a spawnRate parameter of 5 and the other one cloned, with a spawnRate parameter of 20. I guess the thing to do is to use public variable to set them independently in each "instance"/"copy". But when i'm modifying the parameter of one object, the other one also gets affected, any ideas ?
How are you modifying the value: inspector or through code?
was using the inspector through public variables
So you'll need to modify the scene object and not the prefab.
This is what i'm modifying
are you cloning the scen object and not a prefab ?
yeah, i'm not supposed to ?
not if want different values on new object
nah, thats not a good way to do that..
make it a prefab and instantiate that instead
Instantiate returns a clone of the object
for each layer i'd like a different value for exemple but all layers seem to be affected that's the problem
i'll try
So you're wanting to modify through code then. Cache the instantiated object and modify the field for the cloned instance.
layer1 = Instantiate(prefab);
layer2 = Instantiate(prefab);
layer2.setting1 = 10f;
layer1.setting1 = 5f;``` etc super simple example
okay i see
Is there any way to detect collisions between a primitive collider and mesh collider using the ontriggerenter method? The level in my game uses a mesh collider and is an indoor level(I can't make the mesh collider convex), but that means the box collider that I am trying to detect collisions with won't detect collisions for the level.
you could just use physics queries which works on any collider type
I'm getting this weird camera stuttering and I don't know why. I've had this before, someone please help! Here is a video of it, and some of my code ```// Called later and update.
void LateUpdate()
{
HandleCamera();
}
/// <summary>
/// Handles the camera, call in LateUpdate.
/// </summary>
void HandleCamera()
{
// Get the mouse inputs and add them to current rotation vector.
currentCameraRotation.x -= Input.GetAxis("Mouse Y") * CameraSensitivity * Time.deltaTime;
currentCameraRotation.y += Input.GetAxis("Mouse X") * CameraSensitivity * Time.deltaTime;
currentCameraRotation.x = Mathf.Clamp(currentCameraRotation.x, -85, 85);
// Set the camera position to the camera position gameobject.
Camera.transform.position = CameraPosition.transform.position;
// Orientation object is set to the correct rotation, then the players rotation is set to it to prevent player model stuttering, but when setting the camera rotation it doesn't work.
Camera.transform.localRotation = Quaternion.Euler(currentCameraRotation.x, 0, 0);
Orientation.transform.rotation = Quaternion.Euler(0, currentCameraRotation.y, 0);
transform.rotation = Orientation.transform.rotation;
}```
If you're moving through physics, consider updating the camera in the physics step to have it be accurate.
Isn't LateUpdate the best?
Typically you want to move the camera as often as rendering happens, so update or late update is correct. Now, jittering usually happens when the camera or objects in the scene are not moved in sync with it's update.
Since physical objects are moved in fixed update by default, this is often the cause.
That's why there's interpolation option on the rbs. What it does is actually moves the rb in between it's fixed update positions during the regular update.
You should never * Time.deltaTime any Mouse Input
mouse is already framerate independent
I'm saying it as a general thing you should not be doing
idk what ur issue is I havent looked yet
is your character a character controller or rigidbody ?
Rigidbody, interpolation on, using AddForce inside fixedUpdate from Input.GetAxisRaw multiplied by delta time
makes sense why its jittering
your mouselook is def happening faster than rigidbody can update
So... what should I change?
I think mostly the rigidbody rotation
So you're saying I should rotate the player inside Update
if its an option you should use Character Controler since thats moving in Update
shouldbe less of issue jittering
it should be okay, but You tried Update already?
its a tricky problem with rigidbody
I would use character controller but this game is physics based
This is the worst problem 😦
understandable, its for sure the camera though
The weird thing is I copied this code from my old working script...
did you turn on the interpolations and everything?
Yeah, what is everything?
maybe playing around with the Physics settings
In the Project Tab?
yeah project settings
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
maybe something in there
Here is my old code that works for a different game
Wait... I did lerp in that one.
Is that maybe it?
also , s this rigidbody also ?
Yes
wdym?
https://unity.huh.how/lerp/wrong-lerp
this explains better than i can 😛
maybe try rotating player in FixedUpdate with rb.MoveRotation ?
I haven't worked on physics based controllers too much so not sure what fix is
i know its definitely the mismatch in rigidbody move/rotating in physics loop while rotating in update
So, not the camera?
Then why'd you say this
cuz thats the underlying issue
because the camera is moving in a different loop ?
Oh my
It's even worse now when I reverted the code??!??!?!
It seems the rigidbody moving, then rotating the child camera is conflicting with each other
Im rotating the rigidbody in update
also I think camera being parented to a rigidbody doesn't help
parenting and dynamic rigidbodies don't work well
transform following a rigidbody what i mean
What if I damp the position of the camera so it smoothly follows the view
Even smoothing isn't working...
Once I make it higher at least
Can you exclude the camera from viewing the player?
What do you mean by that
now its laggy instead of studdering
I've figured out the problem
It's the rotation of the rigidbody
It just doesn't like rotating with the camera
yes rigidbody is working on FixedUpdate
No but
camera isnt
yes but the rigidbody will still wait till the next physicsupdate to rotate
thats why its outta sync
I'm doing transform.rotation though
and the physics rigidbody has to catch up to that
imagine the physics objects being a seperate scene
I got to go for now, but I really want to fix this 😦
Ok one second
editor has more overhead to run could be messing with physics sync
found this
untested but read last answer from unity employee
Hello guys, one question. If I would like to make a game like tap ninja, it is easier in programming and more logical do do the screen move and not the character or its better to move the character? It seems like games like that the scenario moves but not the heroe itself.. anyone can enlighten me ? thank you
Happens worse in build, I'll check out cinemachine later I used that last time and I think it will fix it
Actaully yeah
I think thats it
yes cause you can pick to update rate of cinemachine brain
if its inifnite runner
ideally you want to move objects towards player
So the scenario moves and the player stays still right?
if you hit a certain amount of position with big float you will get weird issues (float point errors big numbers)
ok thank you very much
usually games get around this problem by respawning player at 000 and then moving the world with it
but for inifinte runner easier to just let obstacles move to you
and terrain for you
ok, thank you i will do like that.
How To Make Car Racing Desktop Game from Cardboard
How to DIY Home Made HowTo Homemade.
Template Link: https://bit.ly/3zjBxvr
PLEASE SUBSCRIBE FOR AWESOME VIDEOS ➤ ❤️ https://goo.gl/2r2fhL ❤️
Official Website: http://www.beginnerlife.com/
----------...
like dis 😄
How does sphereCast with the distance of the cast set to 0(So the sphere has no ray length presumably) differ from CheckSphere
spherecast with distance 0 does nothing afaik
huh
since spherecast doesn't detect colliders it starts out overlapping
Notes: SphereCast will not detect colliders for which the sphere overlaps the collider. Passing a zero radius results in undefined output and doesn't always behave the same as Physics.Raycast.
https://docs.unity3d.com/ScriptReference/Physics.SphereCast.html
why isnt putting [System.Serializable] over my class definition and/or putting [SerializeField] over the variable for the class putting my values in the inspector?
what are you serializing ?
do you have like properties or something
Presumably you are not following the rules here https://docs.unity3d.com/Manual/script-Serialization.html#SerializationRules
Show the code if you want to know exactly what's wrong
(or maybe your code just isn't compiling yet, because you have a compile error)
you don't need the [SerializeField] for a public field.
but uyeah you put [SerializeField] only on an enum declaration, which makes no sense
All the actual fields in your class are private
just to see if it would do it with my enum
enum is a type definition
it's not a field
if you had a field like:
posFromText exampleField; you could serialize THAT
such as the one you have on line 37
yea, thats the only thing serializing
Why are you defining the same enum in two different places though
you have two definitions you don't need two
because it's the only actual field you have
the rules are simple
fields only
the thing on line 19 is not a field
u need above each
and you didn't put [SerializeField] on them either
Again, the rules are here: https://docs.unity3d.com/Manual/script-Serialization.html#SerializationRules
Look at the first rule:
Is public, or has a SerializeField attribute
ok so i changed it back to what i had first and NOW everything is serializing (what i had first wasnt in the ss)
do you plan on using them because you would need a property/method or a public field to use them elsewhere
you wouldn't be able to access the private fields in a script from instance
i put the words public back in the beginning of my class fields and they finally seiralized
odd that it didnt do that the first time i made them public
i thought something changed lol
you likely were missing something else at the time
or had a compile error etc
ah ok
possibly were missing [Serializable] on the class for example
Isn't that the canonical example for foreach?
In this tutorial, we will learn about foreach loops (an alternative to for loop) and how to use them with arrays and collections.
ooop i forgot they need the temp var name
Usually a bootstrap scene is a good idea anyway though
A scene that you load just to set things up
Always loaded as the first scene
even before a main menu etc
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestingPathfinding : MonoBehaviour
{
void Start()
{
print(Physics.Raycast(transform.position, new Vector3(5, 0, 0), 5));
Debug.DrawLine(transform.position, new Vector3(5, 0, 0), Color.white, Mathf.Infinity);
}
}
Why does the raycast return false here? The following script is attached to the smaller box and the raycast comes from it and arrives at the point with nothing but black around it at the end of the drawn line.
If you want to draw a Raycast use DrawRay
If you want to draw a Linecast use DrawLine
Raycast and DrawRay take one position and one direction
Linecast and DrawLine take two positions
you're confusing position and direction vectors
Also for sharing code please format it !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
thank you
thats teh coolest name ive ever heard for a piece of code
i imagine it refers to "pick yourself up from your bootstraps"
lol, its just im always trying to think of clever/ witty names for things
and that ones is pretty dang cool LOL
Yeah. It means it sets things up itself.
Basically the idea behind that phrase.
im weird i guess
(Even though that phrase originates from the idea of lifting oneself by ones bootstraps being impossible)
debugging literally meant removing insect that was fried in early computer 😛
see that stuff is super interesting to me 😄
#computersnappleacts
dang moths blowing my tubes
you know that moth is famous af now
but he didn't expect that shit
coool lol
the bug one.. says Thomas Edison coined it..
but the other source i read was about the Moth and Grace Hopper a admiral in the US Navy
Edison.. always trying to take credit for things 🙄
yeah half this stuff is nonesense
it did come from reddit
im definitely gonna rename my Master scene to Bootstrapper 😄
I've thought about using Bootloader.. but i didn't think it fit well
i'll keep the Bootloader for my embedding stuff
@summer stump
Ball Script --> https://hatebin.com/noizeouboc
(Ball is moving on screenshot, hence the transform values)
This is the camera controller script again
Can you show the ball controller script?
Ah, remove deltaTime from the addtorque calls completely. You will need to reduce your speed variable a lot afterwards
Also consider setting interpolate to interpolate and collision detection to continuous
ok, one sec
idk what that means tho
On the rigidbody component
Eh, lots of practice, and making the same mistakes haha.
Glad it worked!
hey guys, when I use Json system to save my game. where can I find that save inside my computer?
You would decide that. You have to create a path for the file when you create it
Ah, persistentDataPath depends on the os
windows
The docs tell you exactly where it goes
Debug.Log(Application.persistentDataPath); <-- there
Hi guys, I'm trying to write a script for saving and loading a deck of cards and so far I have this logic:
Functions:
- when button is clicked, unity saves string (i).
- when loading said string (i), profile (i) is loaded.
- when loading said string (i), load card preset (i).
is this correct?
This seems logical, but is largely contingent upon whether saving strings is sufficient to describe the cards. This should work as long as each card is accurately represented by a string.
Thanks
What's the easiest way to render geometric primitives in both scene and game view? Just trying to do some testing for a geometric algebra library I'm working on.
Debug.Log(GameObject.FindGameObjectsWithTag("BossHealthText").GetComponent<TextMeshProUGUI>());
Why is it:
NullReferenceException: Object reference not set to an instance of an object
EnemyBoss.Update () (at Assets/Scripts/EnemyBoss.cs:25)
yes I have the tag assigned to the GUI text mesh
that is not even valid C#
that is, I figured it out, I had disabled the components, thanks for the response though
what you posted is not code that would compile
no it is not.
FindGameObjectsWithTag returns an array. You cannot call GetComponent on an array
Can anyone make me an Ultrakill type movement for free? (Please dont ban me or wtv I read through the rules and couldnt find anything about if commisions were bannable)
!collab
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
okay thanks
Yes I figured that out, sorry didnt update the code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class EnemyBoss : MonoBehaviour
{
public float speed;
public float health;
public GameObject enemyMissile;
// Start is called before the first frame update
void Start()
{
transform.position = new Vector3(0.0f, 4.0f, 0.0f);
}
// Update is called once per frame
void Update()
{
// spawn at top of screen and moves left and right continuosly (facing downwards) always facing towards player ship (roatating towards player ship)
TextMeshProUGUI bossHealthDisplay = GameObject.FindGameObjectsWithTag("BossHealthText")[0].GetComponent<TextMeshProUGUI>();
Slider bossHealthSlider = GameObject.FindGameObjectsWithTag("BossHealthSlider")[0].GetComponent<Slider>();
GameObject player = GameObject.FindGameObjectsWithTag("Player")[0];
// move left and right
if (transform.position.x > 10.0f)
{
speed = speed * -1.0f;
}
if (transform.position.x < -10.0f)
{
speed = speed * -1.0f;
// asd asdadsa
}
transform.position += new Vector3(speed, 0.0f, 0.0f);
// rotate towards player
Vector3 direction = player.transform.position - transform.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
Quaternion rotation = Quaternion.AngleAxis(angle - 90, Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, 0.1f);
// shoot missile
if (Random.Range(0, 300) < 1)
{
Quaternion missileRotation = transform.rotation;
GameObject missile = Instantiate(enemyMissile, transform.position + new Vector3(0.0f, 0.6f, 0.0f), missileRotation);
missile.GetComponent<EnemyMissile>().speed = 0.02f;
}
bossHealthDisplay.gameObject.SetActive(true);
bossHealthSlider.value = health / 2;
bossHealthSlider.gameObject.SetActive(true);
//asd
}
}
So I am trying to implement something where the Text Mesh and slider is only created when Enemy Boss object is created, however when i keep these as inactive, it says array is out of index (hence they are not found), is there any workaround this?
Problem you have if No objects are found an index of 0 will be out of range
eg
Slider bossHealthSlider;
GameObject[] gos = GameObject.FindGameObjectsWithTag("BossHealthSlider");
if (gos.Length > 0) bossHealthSlider = gos[0].GetComponent<Slider>();
Also FindGameObjectsWithTag does not have an override to include inactive objects
in general, if I want that a particular gui component to be activated only if a GameObject is added to game, how can i do that?
I wouid use this https://docs.unity3d.com/ScriptReference/Object.FindAnyObjectByType.html which allows for inactive objects and add a specific component to the gameobjects that could trigger it
your other option, which is more efficient, get the relevant gameobjects to inject themselves into a List when they instantiate and remove from the List when they Destroy. That way, if the List.Count > 0 then one of the objects exists
who invented vector flow field pathfinding?
me
hello i made a script that changes a object color when clicked, but how do i change the way a new color value makes a object look? the defuelt is that it adds the color ontop of the original color and blends into it. how would i make the color change solid or ajust things like opacity and blend mode
What kind of object are we talking about
a object containing a sprite rendere
the script changes the color value of the sprite but the color change itself blends into the original color, and doesnt replace it
Why doesn't the Start function get called after returning to a scene that was loaded before. How can I fix this
Hello, does object instantiate - clear events from the copy?
in 3d games are you supposed to rotate the camera with local or world position
like transfom.rotation and transform.localRotation
It depends (tm)
Yes SpriteRenderer color is multiplicative.
The easiest option is for your sprite to be greyscale to start with.
Otherwise you'll need a custom shader.
first person game
If you mean it clears serialized/persistent listeners from a UnityEvent, then no, those get copied. But anything that isn't serialized, i.e. not visible in the inspector, will get cleared.
Start only runs once per object. That's intended and not something that can be or needs fixing
for FP the camera should be a child of the player so local rotation
i am transforming the cameras position to the player personally
if the camera has no parent then local and world are the same
ok thanks
its said to make cam movement smoother
hi. can someone show me like basic code to make a 2d object move left and right? i'm trying to learn unity but when i follow youtube videos to remake something i get an error
here's the code and the error
you should post the error message and the code used, then we can help fix the error . . .
oh lol i was doing that
oh, this is pretty straight-forward. it says the Rigidbody2D does not have a definition or member called Velocity. check the docs for Rigidbody2D and find/use the correct definition/member . . .
ok thanks
ill let u figure it out but its a capital letter issue
gotta use the right casing in these things
the V in Velocity?
click on the link and see how it's used . . .
ok
you say this, but tell them in the same sentence . . . 😄
do you have a bot which puts three dots at the end of each sentence
still gotta figure something out
i just need examples before i start making something my own
i'm not on my pc rn, i'll try things when i get back
but thanks
no problem, you can compare your text with the docs. as bbbbb stated, capitalization matters. C# is a case-sensitive language . . .
How would you achieve constant velocity for a Rigidbody2D? I thought of a backend variable that overrides the current velocity. I dont know if it's good to set velocity in Update() frequently. Movement seems okay in 60 FPS but not in 30-40 fps if i do it in Update()
// Acts like speed. It sends negative version of self to overrideHorizontalvelocity on negative input (left-right)
public float constantVelocity = 5f;
// Overrides velocity in FixedUpdate
private float overrideHorizontalVelocity;
could use a constant force component
if you want to do it in script do it in fixedUpdate
void FixedUpdate()
{
rb.velocity = Vector2.up * speed;
}
Great thank you
you only need to set velocity once, and it will remain constant. you can change it on input instead of every frame in an Update method . . .
would it fr keep the momentum that is useful for me lol
It will remain constant? Gotta try this
tell me if its still smooth despite being out of fixed update
Ah no velocity does not stay constant. Maybe he confused with 3D?
may be able to make it constant with the correct rigibody settings
Okay i will try no friction for you this time
Yeah so i understand that i must edit velocity inside FixedUpdate() now. Thank you
do you know that physics should usually be in fixedupdate
Actually wait friction had worked lmao you were right
Yes. I am getting confused about Physics variables and methods since sometimes some of them may be edited or called outside FixedUpdate()
simple view, read physics in Update. Set physics in FixedUpdate
fixedupdate updates at the same frequency as physics is the reason
Dunno why RandomUnityInvader didn't mention this but the issue is that you need to have your editor configured. That way you won't have these issues.
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
I am new to unity.
if you're looking for somewhere to start learning, then the pathways on the unity !learn site are a great place to start 👇
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
wait am i missing something
raw bytes actually weight more than base64
perhaps unicode is bad format?
if only there were some other way to transfer that data instead of encoding it as a string
if only people stopped complaining about my solutions
if you'd stop trying to turn your audio data into a string just to transfer it from your server to a client, then you might actually get somewhere
i could download it as video but then all the other data would be put somewhere in that video as string regardless
why would you download it is a video? that makes no sense
because 1 link and only 1 link
okay first of all, this is your own restriction you've placed on this problem. second, as i have already told you, if you store the path to the audio in your string that you are sending already you can use that to then download the audio.
so you just have your "one link" that your players will enter or whatever, then your "one link" will contain the level data and another link for the audio. this will also allow you to download level data without immediately downloading the audio data allowing you to potentially set up a preview or whatever because it will be much faster since i'm sure the level data is much smaller than the audio