#💻┃code-beginner
1 messages · Page 188 of 1
we are aware of what you are trying to do
your issue is that you are trying to use a variable that does not exist
what should i do lol
"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: 143
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-2-08
use the variable that does exist
surely you know what a variable is, right?
if the variable is named quitPanel, you can't write QuitPanel or QUITPANEL or quitpanel or florp
the only valid way to reference that variable is quitPanel
what is the name of the only variable you have declared inside that class?
their variable isn't even named quitPanel
They don't even have a lower case quitPanel
They named it something completely different
do i have a variable?
i have no idea
okay it's clear you have no clue what you are doing. so stop, and go do some beginner courses to learn c#. there are some great ones pinned in this channel
Stop. Do not pass GO, do not collect $200. Do the intro to C# course in the pins. You need to know at least what words mean before continuing.
im simply watching tutorials
We cannot help you if you literally do not know what the words mean
And you have managed to not even do that properly.
Go learn the bare bones fundamentals of programming before attempting anything else
Still working on that .-.
Are you using multiple scenes for different areas in your game?
if you go learn the basics you won't run into this issue again because you'll actually understand what you are doing therefore you will save yourself even more time over the course of developing your game
Im using scenes for every room
Okay. I would suggest having a "game controller" object that lives in the DontDestroyOnLoad scene.
The gamecontroller is already DontDestroyOnLoad
It should have a method to load a scene and position the player somewhere in that scene.
The controller and the Player are
yeah well my brain can't handle these stuff, i can forget stuff pretty easily and i can't just wrote bunch of lines without missing a word or symboles or capslocks
You can write a coroutine that:
- fades the screen to black
- loads the new scene
- positions the player
- un-fades the screen
alright well then i'm just going to block you. i don't help people who refuse to even try learning the basics 🤷♂️
It loads scenes through save, and yesterday I was working on the loading position
Oh right, you've got the save data.
Yeah
itemBuilder?.Build();
'?.' on a type deriving from 'UnityEngine.Object' bypasses the lifetime check on the underlying Unity engine object
What does this warning mean? Is it possible to use it if you learn the side effects or is it rather a no-go
i.e. is start not called?
who said i refuse lol and why "block" i don't get it
no, it does not use the overloaded == operator from unity so it can not check if the object has been destroyed, it just does a pure null check. destroyed objects are not actually null, they just return true when comparing to null with == because UnityEngine.Object has overloaded the operator
because you're refusing to take any of the advice you're being given and spamming emojis at us
im not lol
[System.Serializable]
public class SaveData
{
public string sceneName;
public Vector3 position;
}
IEnumerator LoadFromSave(SaveData data)
{
AsyncOperation handle = SceneManager.LoadSceneAsync(data.sceneName);
yield return handle;
Player.instance.transform.position = data.position;
}
Could be as simple as this.
I would suggest making SaveData store all of the important information (e.g. upgrades, quest progress, etc.)
and then have a smaller class for where you should respawn at
Whats thr IEnumerator again? I remember seeing it once while making a timer
SavePointData, maybe
Ahhh thank you gotcha. Just as an aside, though, wouldn't it be easy for Unity to overload ?. or does C# not support overloading that operator
i really apreciate u guys helping me out and im just chilling around, and im also learning btw i was joking
not possible
IEnumerator means that this method returns an enumerator. An enumerator is an object that can give you a sequence of values.
The method runs until it hits a yield statement, then pauses.
and for the emojis that's just me do that most of time
If you pass an enumerator to StartCoroutine, Unity will ask it for a new value every frame (by default). This resumes the method until it hits another yield
But you can also yield special values to change that behavior. Notably, you can yield an AsyncOperation to make the coroutine wait until the operation is done
The SaveData would have to be destroyed on load though, so I can give it a different value every instance it appears
SaveData is a plain old C# class.
It's not a unity object at all; there's no notion of being "destroyed"
You'd just need to store it somewhere that you can always access.
So, for example, I would hang on to the current save data in a static field (or put it in the singleton game controller)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MonkeButton : MonoBehaviour
{
public GameObject Object;
public Material red;
public Material white;
public AudioSource sound;
void OnTriggerEnter()
{
Object.GetComponent<Renderer>.material = red;
sound.Play();
}
void OnTriggerExit()
{
Object.GetComponent<Renderer>.material = white;
sound.Stop();
}
} This is my full script
So like, I assign it to both the destroyable game object and a DontDestroyOnLoad?
and what is the error
I want to set the rb (rigidbody) to 0,0
please help
You don't need a game object at all. SaveData is just a blob of data.
Assets\Scripts\MonkeButton.cs(14,16): error CS0119: 'GameObject.GetComponent<T>()' is a method, which is not valid in the given context
public static class Whatever {
public static SaveData someCoolData;
}
right. and how do you invoke a method?
this is the error
Whatever.someCoolData holds a SaveData. Bam.
SaveData is not a unity object. It isn't instasntiated or destroyed.
idk
() is used to invoke a method
[CreateAssetMenu(fileName = "ItemSO", menuName = "Tool", order = 0)]
public class ToolSO : ItemSO
{
[SerializeField] private int _maxDurability;
public int MaxDurability => _maxDurability;
public int CurrentDurability { get; private set; }
public override ItemSO Build()
{
return copy of this and:
CurrentDurability = _maxDurability;
}
}
How would I do the pseudocode in Build() for a scriptable object?
thx
Instantiate is what you're looking for.
It copies any unity object.
Okay thanks I'll try
But for it to do anything it needs to be assigned, no?
where should i put the () then?
Sure. You need to create a SaveData object and put some data in it
and then you need to store it
read your error message again then read the line that the error is on
I'm not a huge fan of storing mutable data in scriptable objects like this. Instantiating the object does create a fresh copy you can modify as you want, but...
To create a new instance of something you need to use the new keyword
I prefer creating a separate class that references an ItemSO
public class Tool : MonoBehaviour {
public ToolSO toolData;
}
e.g.
On the line that's underlined in red in your IDE
Exactly what I was saying. The SaveData object would need to be DontDestroyOnLoad, wouldnt it?
SaveData is not a unity object. It cannot be destroyed.
Do you mean the thing that holds the SaveData?
Object.GetComponent<Renderer>.material = white; this is the line wher should i put the ()
read the error again
Thanks!!
The SaveData OBJECT, not the script
If you want to store it inside a unity object, then yes, you need to make sure this object isn't destroyed (and that you always have a reference to it)
it sounds like your'e confused about the terminology here
Ok cool
A lot
The disadvantage of this is the typing. Right now most items are just "normal SO data" objects, so the inventory expects ItemSO. ToolSO is of that type but if I create a monobehaviour to handle the mutable data, it wouldn't be and I'd have to rework the entire architecture.
Assets\Scripts\MonkeButton.cs(14,9): error CS1955: Non-invocable member 'MonkeButton.Object' cannot be used like a method.
then it gives me this error
you've put the () in the wrong place. the original error actually showed you where to put it
Object().GetComponent<Renderer>.material = white;
sound.Stop(); i did it here
yeah that's clear from the error
your variable is not a method. you invoke a method
The script is the text file that contains your C# code. In your case, it's going to define a single class called SaveData.
SaveData doesn't inherit from UnityEngine.Object, so it is not a unity object.
You can construct a SaveData like this:
SaveData myData = new SaveData();
You now have an instance of SaveData in a variable named myData. myData holds an object, and the type of the object is SaveData.
You need to store this object somewhere that you can always access. A great choice would be your game controller. Your game controller is a Unity object, and you put in the "dont' destroy on load" scene so that it doesn't die when you change scenes.
Assets\Scripts\MonkeButton.cs(14,16): error CS0119: 'GameObject.GetComponent<T>()' is a method, which is not valid in the given context this is the old one what should i do
this error literally shows you where the parentheses go. if you cannot understand that at this point, then stop what you are doing and go through the beginner c# courses pinned in this channel
(the old error)
please learn to read while you're at it
public class GameController : MonoBehaviour {
public SaveData currentSaveData = new();
void Awake() {
// consider loading a save file here.
// otherwise, just put the default scene and position in!
}
public void UpdateSaveData(string sceneName, Vector3 position) {
currentSaveData.scene = sceneName;
currentSaveData.position = position;
}
}
It might look like this.
Where does it shows you
why don't you read the error and find out?
Did you try looking at the parenthesis
To see where it expects parenthesis
my english is 5% good idk what to say
you don't need to understand english to see where the () are in that error message
just idk where to put it
You could tell him to figure it out without beimg so aggressive
U have to put them in the end of the name of the method you are trying to call. For example:
if(insert condition here)
{
Method();
}
void Method()
They are calling GetComponent. The angle brackets are confusing them I guess
it's a good thing that their error message shows where to put the parentheses when calling GetComponent<T>()
Sometimes they are just a little slow. Still no need to be rude
your input was not needed here, nor were the pings
Nor did it even help them... because it explained something different
Is there any reason why adding transformations constraints to a rb dissables the collisions with said object?
that shouldn't affect collisions like at all
is the issue that your collider is actually passing through an object it should collide with, or is it the physics messages like OnCollisionEnter not being called?
where do I map my uv points on my plane mesh? do I map them on every vertex or what?
Like I have this thingy am I want it to have a capsulle collider, and it needs a rb cause all enemies do, is to hanlde knockback and collisions with the proyectiles; but if I use the normal rb, the item gets pushed away form the floor due to the capsule collider, so I checked the freeze position boxes (cause it is turret and is not meant to move anyways) and then it just ignores all collisions with everyting
Like that shouldn't do that right?
what do you mean by ignores all collisions #💻┃code-beginner message
Literally all collisions, nor the rb collisions, nor the trigger collider with the proyectiles
Everything is ignored
Just phases through
did you make the object kinematic
actually show the objects that should be colliding at runtime
If I do that it doesn't trigger the proyectile collision
But does collide with the rbs though
right and that is why i asked since you aren't bothering to provide any actual details.
you need to show the objects or provide any useful details if you want to get help. i do not want to play 20 questions with you just to get some absolutely basic info
This with a non-trigger collider and non-kinematic rb
The player gets "gently" pushed out
typically when someone wants to see an object, they want to see the inspector
If I use kinematic, the player cannot phase through, but the proyectiles do
This is the inspector
I don't know what you want to see there since I am like literally changing it everty 2 mins so...
now show the projectile and the player
the projectile is a trigger collider. it will phase through anything because it does not physically collide
as for the player, it probably depends on how you actually move it
As far as I know it does with OnTriggerEnter(); if the object has a rb that's it
This does work with objects with the same setup but unfreeze constraints
the constraints have nothing at all to do with trigger messages. it just prevents physics from moving the objects on those axes. first you need to ensure you are receiving a physics message
then you need to make sure that your logic is correct. for example, why are you checking for a specific layer there? why not check for a tag or a component instead
I.... don't know, I created a layer AND a tag for both the enemy and the player, I think I had a reason for it before but I don't actually remember
I think it was to work with raycasts
also what object is that component even attached to. it seems like it should be attached to the turret, but your previous screenshot did not include anything other than the collider and RB
This script is attached to the proyectile; if you are refering to the BasicEnemyBehaviour is the generalist script for all enemies, so all of them should have it
your turret does not
also how are you even assigning the enemyCollisionLayer? because it isn't visible in the inspector
The function to destroy doesn't need it, just the rest
In the general proyectiles class; it stores all potential layers of collision for all proyectiles
show how you assign that
Hey there everyone, do you guys have any idea on why when my weapon reaches lvl 2 it instantiate a clone of the weapon, but it's inactive?
It should be like lvl 1= single weapon. lvl 2 = double weapon.
https://gyazo.com/f3d671f441ceec997be436b47e041fee Screenshot of the cloned object not being active when instantiated.
https://hatebin.com/mdcwyqpcse weapon code
Is the prefab active
ye it is
are you certain you don't have any code on the prefab causing it to disable?
btw, perfect use case for a dictionary
[SerializeField] private float purpleGemChance = 0.05f;
[SerializeField] private float redGemChance = 0.1f;
[SerializeField] private float blueGemChance = 0.3f;
[SerializeField] private float greenGemChance = 0.4f;
perhaps in Start?
Is there a script on the prefab that has it deactivating itself
Show code for Orbit
ye
Oh
gameObject.SetActive(false);
I didn't see the class name, I thought we were looking at something else
Yeah that'll do it
okay so that's what's setting it to unactive
Is just the raw number manually >.<
It does work, I assure you of that, is working for other objects
prove it. put some logs in OnTriggerEnter and log what is being hit and its layer
I'm using a dictionary already but for gems there's only one
actually not it should one for each gem
It does work with anything on the Layer, doesn't need the enemyscript
with the turret . . .
hi, let me ask you something. when we make a multiplier game on this steam, we make the server that creates the lobby. can we make this a steam server server, so no one in the lobby will be a server.
[NonSerialized] would be better than HideInInspector
#archived-networking for networking related questions
but steam does not host servers for you
okey, thanks
Oh, it does collide now, it needs an enemy script or be labelled as a wall, don't know why, shouldn't
Should check that
What's the actual difference?
A serialized field is stored in the prefab/scene
Unity remembers its value for each instance of the component.
[HideInInspector] just stops the field from appearing in the inspector. It can still be serialized.
hideInInspector still serializes it
So if you change = 6 to = 5, all of the existing instances of the component will still have a 6 in that field
the field initializer is overwritten by the serialized value if one exists
Not only that, because it's hidden in the inspector, you have no way to change it back
unless you change it in code
So, since I am not changing it at all it should be NonSerialized?
but then you might as well just not serialize it at all
Do you need a unique value to be remembered for each instance?
If not, make it non serialized
No, the layers are gonna remain the same all the time
sure - realistically I'd just recommend making a const though:
public const int WallCollisionLayer = 6;```
So the children can acces it
if (inventorySlot?.Item is not ToolSO tool) return;
If inventorySlot is null, will this return?
Though could be just protected
protected
you can't reliably use ?. with unity objects
a destroyed unity object compares equal to null
is not doesn't work in unity does it?
but it's not actually null
is returns false for null
is not returns true for null
This is not a MonoBehaviour
(or plain old record)
So like that is the optimal way then?
ohh
ScriptableObject still inherits from UnityEngine.Object so it can still be destroyed
It's not a ScriptableObject either
It's just a class
A C# class with no inheriting classes
i need to be able to get collisions on an gamobject but i want to still be able to pass through the gamobject but when i set istrigger to true it doesnt get the collision and if its falls u cant walk through it
istrigger works fine, but u must have a rigidbody.. preferably on the other object..
or to prevent it from falling you can lock the constraints (x,y,z) axis
hi, don`t know where to ask this but how can I make a transparent img object? So an object thats just a png without background
in the import settings when you select the object there's options for how to use alpha values
k thanks
i tried it but it doesnt register till i turn istrigger off
OnCollision would work if u turn off isTrigger
{
Debug.Log(hit);
Vector3 newPosition = new Vector3(
Mathf.RoundToInt(hit.point.x) != 0 ? Mathf.Round(hit.point.x / 2) * 2 : 2,
Mathf.RoundToInt(hit.point.y) != 0 ? Mathf.Round(hit.point.y / 2) * 0 : 0,
Mathf.RoundToInt(hit.point.z) != 0 ? Mathf.Round(hit.point.z / 2) * 2 : 2);
floorBuild.position = newPosition;
if (Input.GetMouseButtonDown(0))
{
Instantiate(floorPrefab, newPosition, floorBuild.rotation);
}
}``` i have to press mouse 0 like upto 5 times to register. is et mouse button down correct
the mesh you render it on must also use a transparent shader / have transparency selected
read the error
alright
its pretty big syntax error
but i want the object to be passthrough
or use alpha clipping on opaque shaders
if (Input.GetMouseButtonDown(0))
{
// now raycast
Instantiate(floorPrefab, newPosition, floorBuild.rotation);
}
}```
line 24 ;
are you just randomly guessing your way through this?
ya, thats why i said IsTrigger... ur saying it only works when thats turned off... well the method that would work if the IsTrigger is turned off is OnCollisionEnter not OnTriggerEnter
dont need to check if its true, its already doing that
but a trigger is what u want.. your setup is just wrong apparently
kinda. there was no input key in unity manual
but how do i make the object itself dedect collisions and be passthrough
put the OnTriggerCode on the thing with the trigger collider
what doesnt work about it?
it is
and have a rigidbody on the other thing..
#💻┃code-beginner message
this guide tells u what u should do..
when I press enter it wont switch between first person and second person cameras
theres a rigedbody on both
if(person.enabled) that is checking if true. if(!person.enable) that is checking for false.
why have a rigidbody on the trigger object?
i thought first that that was the problem
show the code, and a screenshot of the object / trigger/ and its inspector
are u using enter on the KeyPad ?
i have keyboard
in mac, i do not have snippets for alot of functions can anyone help?
wait okay. i didnt know what keypad was my bad
i have downloaded the snippet extensions
i saw key and thought keyboard
theres two different enter keys
show the heirarchy and the sceneview
What is the correct way to make unity allow me to delete/remove/whatever, completely remove a gameobject from the scene in edit mode?
I keep running into errors where it keeps telling me thats not how to delete a thing, but it wont tell me how to delete a thing
DestroyImmediate doesn't work
"InvalidOperationException: Destroying the root game GameObject of a Prefab Asset is not permitted.
InitiativeTracker.ClearInitiative () (at Assets/Scripts/UI/Initiative/InitiativeTracker.cs:147)"
click the edit collider button
The result I want is the result you get from selecting it and hitting the delete key
i dont see the collider in teh screenshot.. its size is .2 i wonder if its too small.. or underground or something
make it wider
yeah there is a regular enter buton key one, did you fix it ?
ur rigidbody has a collider.. so if the code is in the Goal Script it should detect it just fine
i set it to 1 it doesnt dedect it
when you press the play button the collider stays in the correct place?
show the code for GoalScript
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GoalScript : MonoBehaviour
{
public int GoalNum;
private void OnCollisionEnter(Collision collision)
{
Debug.Log(collision.gameObject.tag);
if(collision.gameObject.tag == "Ball")
{
GameManager.Instance.Goal(GoalNum);
}
}
}```
Configure your code editor so it works with Unity. !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
bro.. thats nots OnTriggerEnter
oh i thought i did it before
im still trying though i think i will fix it
Errors will be underlined red in the code directly when it's done
put Debug.Log inside
read the docs for GetKeyDown
make sure its runninig
i said that wayyy up here
Make sure to use the correct method.. if ur using IsTrigger.. you need OnTriggerEnter
OnCollision is just that.. like if the ball were to strike the box and roll backwards that would be OnCollisionEnter
oh thanks that was the problem didnt know there where diffrent functions thought both must be oncollision
well for one you actually spelled it wrong on line 13
you also spelled Start wrong
Look at any basic C# code example. You do not put ; after the parameter list for a function like you did on line 16.
alr
definitely learn a c# tutorial before starting unity
Spelling is a requirement for programming
and level with player and everything
There is no "close enough"
I found the problem, the problem is that my list of gameobjects is not a list of gameobjects
you have to spell the words right
not sure on this one
Dont think thats right because i need to see where the ghost object is going to be positioned. then the instaiate just places the real object in that current positon
debug your bool of raycast and see Why you need so many tries
I finished the first juniour programming lessons and the car game is cool, currently I planted the obstacles but I want to make it an infinate loop where it generates obstacles in random places, I don’t know where to start
visual studio is far better than vs code. it's easier to configure, less likely to break, and is a fully featured IDE right out of the box
ok thanks :D
i think your talking about procedural generation?
if yes thats where u start learning how to make infinite loops for generating obstacles
but how to code it? idk im still new i just know the idea
var adjacentObjects = Physics2D.OverlapBoxAll(
transform.position,
new Vector2(1.1f, 1.1f),
0f,
_connectableLayers
);
Why does this collect the game object itself? It has the same layer and is within the bounds, of course, but why would Unity include the calling object itself?
is the method Awake same as the method Start?
Physics2D.OverlapBoxAll is a static function.
it has no concept whatsoever of "the object that called the function"
they are not the same no
they both run once, thats the only common thing
For initializing the object itself, use Awake
either, but awake best for initialization
Ah okay thanks
For initializing things that depend on other objects already being initialized, use Start
So how would I filter it out?
foreach (var adjacentCollider in adjacentObjects)
if (adjacentCollider.gameObject is gameObject) continue;
In this case gameObject does not seem to work in that context
like a variable?
adjacentCollider.gameObject is gameObject ?
Really vague question.
say you load your ScoreScript score by PlayerPrefs in awake, then you have another script like UI to read the score, thats where you use Start
uiText.text = thecoreScript.Score.ToString() (simple example, obv you would use events :P)
Are you changing it to something that depends on some other object being initialized?
GetKeyDown was inside fixed update didnt know that would break it. only added it there because i needed inside raycast. thanks fixed it
yes never a good idea to add one frame events inside a physics update 😛
I keep my inputs polling to Update
the best way to learn , start testing it yourself and see
yeye
im tryna understand before i implement
and add stuff to figure out more stuff
I was eating sorry for late reply.
you have a shiton of errors
public class ConnectableObject : DestroyableObject
{
// Called when Instantiate is used to create this instance
private void OnEnable()
{
ConnectToAdjacentObjects();
}
private void ConnectToAdjacentObjects()
{
Debug.Log(transform.position); // <--- very wrong output
}
Can anyone tell me why the position is so incredibly wrong? In fact, if I instantiate multiple objects, they all have that strange position
yeah i know 😄
also debug log wont show message
well then its not surprising stuff isn't working lol
yeaa
where did you assign the firstperson and secondperson
i actualy tried to put debug log everywhere but it wouldnt work so i asked chatgpt
keep in mind that the position you see in the inspector is the localPosition
debug doesn't matter right now, cause this script is throwing errors because those two arent assigned
this doesn't show me how you assigned them
in the script
show me the script on the gameobject
public Camera firstperson;
public Camera secondperson;
this is just declaring them
this is for ship
main ship we control
derp moment
But why is it always the same position no matter the instance?
what moment? 😄
how should i know? you haven't shown how you specify the position when you spawn it. you just show where you log the position
show where you put it on the gameobject @timid saffron
the inspector..
read what the error says
public void PlaceConnectableAt(ConnectableObject prefabToPlace, Vector2 position)
{
var copy = Instantiate(prefabToPlace, transform);
copy.transform.position = new Vector3(
Mathf.RoundToInt(position.x),
Mathf.RoundToInt(position.y),
10f
);
}
which in turn is called by
public void Interact(Vector3 mousePosition)
{
var playerPosition = PlayerMovement.Instance.FeetPosition;
var roundedMousePosition =
new Vector2(Mathf.RoundToInt(mousePosition.x), Mathf.RoundToInt(mousePosition.y));
var distance = Mathf.RoundToInt(Vector2.Distance(
roundedMousePosition,
new Vector2(Mathf.RoundToInt(playerPosition.x), Mathf.RoundToInt(playerPosition.y))
));
if (distance > _rangeInMeters) return;
ObjectPlacer.Instance.PlaceConnectableAt(_prefabToPlace, roundedMousePosition);
}
The position works absolutely as intended because I can see the objects rendered perfectly on screen, it's just the print statement that's off for some reason
it says im using a vector2?
Rigidbody2D uses a Vector2 for velocity. it has no z axis
so do i make z as 0?
Vector2 doesnt have a z
its 2 floats
inpsector
just get rid of it
no the struct doesnt have it at all lol
you should be doing new Vector2 not new Vector3
Unity turns V2 into V3 and 0s out the Z but thats if its not 2D
what do you mean the print statement is off? it is literally printing the world space position. that position is correct for the object the component is attached to
oki
@rich adderdid i send you what you wanted?
Well it's the same position for every instantiated instance. That cannot be right
do you see
you are trying to use something thats not assigned
the computer doesnt know which camera you want
Here is an example
don't make assumptions about what is or is not correct. it's obviously correct at the time you print the position. remember that OnEnable is called before Instantiate returns
so it's printing the position of the parent object because that is where the object is when OnEnable is called
damn cool. it works now
although i can only do it once ill work on it now
minor details i miss 😄
So I must create a custom method AfterInstantiation to delegate the OnEnable stuff to?
or you could just specify the position in the Instantiate call instead of on the line after
No, there is more that needs to be done on instantiation
I just left it out for simplicity here.
Thanks for the help :)
stop truncating your code when sharing it. jesus that's annoying. what if the issue was caused by something you left out?
"hey what's causing my issue?"
share the code
"here's only part of the code that i'm going to assume is the part that is at fault because i totally know what is causing it which is why i'm asking for help"
Yeah no. The log was literally the first thing of the method.
we did it
this is the code
im pretty sure it can be written better but
it works
if(Input.GetKeyDown(KeyCode.Return))
{
firstperson.enabled = !firstperson.enabled;
secondperson.enabled = !secondperson.enabled;
}
would work assuming they are in the correct state when you start
can someone help what's causing this error? these are the codes
damn
this makes a lot more sense
i gotta think outside the box sometime soon
Something on line 27 of playerCombat is null but you're trying to use it anyway
nah you gotta get into my mindset. think inside the box
bunny stats are null, whatever that is, most likely
you're using that in your newHP setter
And dear god, it hurts my eyes to look at how you name these methods
yeah the _ prefix should be reserved for non-public fields. it should never be used on anything public or on methods ever
can someone help me with something
my character in unity wont move properly even tho i did exactly as said in the tutorial. he just starts to jitter and get stuck whenever i press wasd
thanks for the help and advice (although i just barely understand what's causing it) also sorry for the naming lmao, im still new but ill fix it
show relevant !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 System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Playerr : MonoBehaviour
{
public float moveSpeed;
public bool isMoving;
private Vector2 input;
private void Update()
{
if (!isMoving)
{
input.x = Input.GetAxis("Horizontal");
input.y = Input.GetAxis("Vertical");
if (input != Vector2.zero)
{
var targetPos = transform.position;
targetPos.x += input.x;
targetPos.y += input.y;
StartCoroutine(Move(targetPos));
}
}
}
IEnumerator Move(Vector3 targetPos)
{
while ((targetPos - transform.position).sqrMagnitude > Mathf.Epsilon)
{
transform.position = Vector3.MoveTowards(transform.position, targetPos, moveSpeed * Time.deltaTime);
yield return null;
}
transform.position = targetPos;
isMoving = false;
}
}
!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.
Look up some C# naming conventions. Readable code is your first step towards getting better..
i was trying to get the _health from the bunny stats which has a value of 25 so i dont really get it
Did you set the bunny stats to some instance or do you expect your code to just guess where to get it from?
okay thanks, so i wont hurt anyone eyes anymore in the future lmao
!screenshots
No
Be mindful, if someone requests your code as text, don't send a screenshot!
what are u even saying
please learn to read
read the bot
i think i figured it out
thanks a lot

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Playerr : MonoBehaviour
{
public float moveSpeed;
public bool isMoving;
private Vector2 input;
private void Update()
{
if (!isMoving)
{
input.x = Input.GetAxis("Horizontal");
input.y = Input.GetAxis("Vertical");
if (input != Vector2.zero)
{
var targetPos = transform.position;
targetPos.x += input.x;
targetPos.y += input.y;
StartCoroutine(Move(targetPos));
}
}
}
IEnumerator Move(Vector3 targetPos)
{
while ((targetPos - transform.position).sqrMagnitude > Mathf.Epsilon)
{
transform.position = Vector3.MoveTowards(transform.position, targetPos, moveSpeed * Time.deltaTime);
yield return null;
}
transform.position = targetPos;
isMoving = false;
}
}
character wont move he just jitters
you never set isMoving to true so you start that coroutine every frame
You're starting a new coroutine every frame
this is way overcomplicated
what am i supposed to do
go back to the tutorial you copied that from and set isMoving to true in the same place the tutorial does
the tutorial guy said this do u have a better variant?
private void Update()
{
if (!isMoving)
{
input.x = Input.GetAxis("Horizontal");
input.y = Input.GetAxis("Vertical");
if (input != Vector2.zero)
{
var targetPos = transform.position;
targetPos.x += input.x;
targetPos.y += input.y;
}
}
transform.position = Vector3.MoveTowards(transform.position, targetPos, moveSpeed * Time.deltaTime);
}```
There's absolutely no reason to use a coroutine here
What tutorial is it
bad tutorial - or you followed it wrong
Please watch the video till the end, then do it yourself :D
Chapters:
00:00 - Intro
01:06 - Concept explanation
03:08 - Importing character sprite
06:05 - Creating the script file
09:00 - Coding the movement
25:35 - Testing the game
Links
Visual Studio Download: https://visualstudio.microsoft.com/downloads/
Character Sprite: https://github.co...
holy hell they actually did copy the tutorial correctly ah looks like that isMoving bit was corrected after the part i saw
You just didn't follow the tutorial properly
you skipped the isMoving = true; line
so that broke it
huhhh
in the future, copy the code as it is in the tutorial
do i just write that and boom
"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: 144
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-2-08
thanks tho
W thing
first code 🔥 😂
the background noise makes it better
This function is always returning the number in the box as an argument instead of the selected index of the dropdown. The object in question is a TMP_Dropdown
Is this a Unity question
Use the dynamic function instead of the one with a hard-coded value
no its just a joke
5 × 2 = Hello world ? I've been lied to all my life

it's the only option in the properties for an object, is it something I have to enable somewhere else?
the docs say it should pass the index value
ah, missed that message thanks
var roundedPosition = new Vector3(
Mathf.RoundToInt(position.x),
Mathf.RoundToInt(position.y),
10f
);
var placedObjectsAtPosition = Physics2D.Raycast(
roundedPosition,
Vector2.down,
1f,
_placableLayers
);
if (placedObjectsAtPosition.collider is null)
{
var copy = Instantiate(prefabToPlace, transform);
copy.transform.position = roundedPosition;
copy.AfterInstantiation();
}
else
{
Debug.Log("Already exists");
}
Could someone help me with the raycast? I think some value is not what it should be because some tiles are incorrectly "found" and therefore the player can't place an object there.
why are you using Raycast here exactly?
yeah that should just be an OverlapBox
To check if there already is a "farming field" where the user clicks
I think it should just be... a position calculation followed by a Grid.WorldToCell()
or a CheckBox if none of the info about what is there is actually needed
User clicking query should be Physics2D.GetRayIntersection
It's not actually a tile. Those are all sprites
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit2D hit = Physics2D.GetRayIntersection(ray, Mathf.Infinity, _placeableLayers);```
Raycast is for rays within the 2d world
GetRayIntersection is for this.
Hey, I am currently working on a scoreboard that should increase when winObjects tag is checked/found, it increases to one and stays at 1.
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class landmineCounter : MonoBehaviour
{
public GameObject mineDefusedCounter;
public Text DefusedCounterText;
public float defusedScore = 0f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "WinObjects")
{
Debug.Log("Collision detected with WinObjects");
defusedScore ++;
Debug.Log("Score increased to: " + defusedScore);
DefusedCounterText.text = "" + defusedScore;
}
}
}
But the roundedPosition in my example already has the position calculated
So the mouse doesn't really play a role anymore
It should just check if in that position, there is a gameobject with the layer
but you're rounding from the wrong position
do this to get the right position, then round
Oh wait you're doing a raycast to see if there's an object there?
This is kinda... all backwards
You should have a grid
and look up the grid coordinates
Yes
I.e. the objects places should be looked up in a 2D array or a Dictionary
using physics for this is going to cause a lot of issues, performance being one of them
Ah so a simple check if there is a sprite in the list with key [position]? Yes, that could work
ANd I highly recommend using this component:
https://docs.unity3d.com/Manual/class-Grid.html
This makes converting world space and grid coordinates and vice versa super easy
x is a completely separate variable that is not part of the float struct
you just happen to have a float called x
I'd like to make it so when the player selects an option in one dropdown menu, two other dropdowns are set back to their default value. When I run this with the setAllDropDowns0(); enabled, on selecting an option the dropdown remains open and all options when selected remain selected until the entire dropdown has checkmarks
the reason i assigned a flot to x y z was because:
there are beginner c# courses pinned in this channel. please do them
because, again, your variables that happen to be floats are not part of the float struct
am doing junior developer
start by learning the basics of c# before learning unity
🫡
Hey there, I'm making a 2D platformer and I made a custom collision detection script using raycasting. Now I'm wondering if I should set the speed of my character before or after my collision detection?
The code for adjusting the character's velocity to be more clear
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/floating-point-numeric-types
Show me where in the definition of float there is a property called x
hello, i know the basics of c# and want to learn unity, should i start with the "junior programmer" course or something else?
start with the essentials pathway first then do the junior programmer pathway. essentials covers a lot of stuff for the editor and just game development in general
It's also good to get some reinforcement.
If your code is simulating a collision, then you want to change velocity after collision.
Mastery comes through repetition!
Alright and why exactly? I can't really find defined explanations on the internet
idk exactly what your goal is here. it sounds like you want to simulate the impulse of a rigidbody colliding with an object of infinite mass
Well I have collisions with raycasts. For example if I'm running right and hit a wall, it will detect the wall and place my character perfectly against that wall using the hit.distance of the ray.
It might help to know how my physics engine handles it. My custom physics engine does the following:
- If object is in reference frame, Cast to try to translate, without modifying velocity.
- Based on velocity, calculate desired displacement for one step of simulation (of fixedDeltaTime)
- Cast to move by that vector, or until the first thing we hit. Whichever comes first. If we got a hit, update velocity based on the angle. Move object there.
- Collide and slide algorithm: Repeat step 3 with whatever remaining displacement, deflected along the surface normal we hit.
also, in 2D, if you have simple colliders, use Collider2D.Cast instead of Raycast. Collider2D.Cast is only slightly more expensive, but gives better info for moving the whole thing.
I can send code at some point, because this algorithm is complex because of the edge case where the tiny amount of accuracy in how much we move makes a big difference. But my computer is in the shop right now.
like, if your RaycastHit2D says to move by X, and you move by X, you’ll be in contact but not able to cast or something. There’s a correction factor so you move just enough to be in contact to trigger collision callbacks, far enough to cast again without just reading the same hit again
This is because Physics2D is based off of Box2D, which gives every polygon an edge radius (for math reasons), and this edge radius becomes extremely important when you want to move an object to be right in contact with another
Alright interesting. Seems a bit complex indeed haha, but I'll try some things out
I can also show you my code to see what should be changed
As far as your original question goes, for modifying velocity, as long as you calculate initial desired displacement based off the previous velocity, it doesn’t really matter when you change velocity before or after. As long as you get everything in before anything that depends on velocity can access it (eg physics sim)
But you usually want to do it after you cast because you need the normal of the hit to modify the velocity
sure. sorry this is very complex lol
Would it be better if I send it in DM or here?
once my computer comes back from the shop in a few days, I can send you code that might aid you.
Awesome
DM or pastebin here
Alright I'll DM it
i do warn that it gets complicated
I know, hopefully I can wrap my head around it
This might give some guidance. This code will not be complete to copy for 2D because of the edge radius thing, but it gives the initial idea:
https://youtu.be/YR6Q7dUz2uk?si=6Oti9sTNvVHU7dli
How to make actually decent collision for your custom character controller. Hopefully you find this helpful and people will finally stop saying "jUsT uSe DyNaMiC rIgIdBoDy!!!1!!11!!"
Chapters:
00:00 - Intro
01:09 - Algorithm
05:11 - Implementation
Improved Collision detection and Response (Fauerby Paper):
https://www.peroxide.dk/papers/collisi...
to get a random element from an array, do i need to do myArray[Random. Range(0, myArray, Length)]; or myArray[Random. Range(0, myArray, Length-1)];?
most resources online dont subtract one from the array length, but it dosnt make any sence to me, since the index of the last item should be one less than then the length of the array
Random.Range for ints is exclusive
(0,5) for example will generate from possible numbers: 0,1,2,3,4
so you don't substract -1
is there a way to see the type of a component in the editor?
I am using a VFX component and I want to reference it in code, but I'm not sure what data type to reference it by
like when I do GameObject.GetComponent<T>(), I'm not sure what the T is supposed to be
Usually searching for
unity [your component name] scripting api
In your search engine will show a link where you can see what type it is, and which namespace it's in
Example for "particle system"
It's class ParticleSystem, and you need using UnityEngine to reference it
ah ok thanks, I think I found it, I was looking for visualEffectAsset I think
I think a quicker way to do it than just googling it i s clicking the little question a mark icon in the editor, that opens the API on that component directly
hi
when i tried to switch my project platform from windows to android the sprites started to look weird, does anyone know why?
The choice of platform is probably affecting how the textures get compressed
This isn't a code problem. You should ask about it in #💻┃unity-talk
Hi there 🙂 Would anyone happen to know if it's possible to have a nested class utilise [ExecuteInEditMode]?
I basically have a class with some logic being done on Update() in the Unity Editor, but when I nest this class in another script, it stops executing in Edit Mode
ExecuteInEditMode will not affect NestedUpdater because it does not inherit from MonoBehaviour so there's nothing to execute during edit mode. You could have the ParentClass component execute in edit mode and call NestedUpdater's Update method though
Aah that makes a lot of sense, thank you 🙂
can you suggest a vid for makeing guns
There are many tutorials out there, but it really depends on your use case. There are many things to consider, like are you making complex guns? Will they have weapon parts, recoil, ADS?
well in say gun more like a hand that tags peple and has a cool down
keep in mind that GetKeyDown is only true for the first frame the key is held down. so the next frame, if this code executes it will set the Speed parameter back to 0
what can i do to fix it ??
Gonna be awfully hard to notice a change in the animation that's 1 frame long
instead of checking if the key was pressed this frame, check if the key is currently held with GetKey
Yo can anyone help me in #archived-urp ? I have a massive issue with my camera but this channel is more active and I can't post non-code-related things here. It's late where I live and I need help
don't crosspost
How is this crossposting if I'm not sneding any unrelated stuff here?
I'm just asking for more help
Last anyone even touched the URP channel was like 4 days
you're literally posting in another channel to get help in the channel you posted your question in. that is considered crossposting and you are posting off topic since it is not code related
Nevermind apparently it's only been a day
I guess I can wait
well in say gun more like a hand that tags peple and has a cool dow
the animation change only if it's finish you know if we can "break" an animation
Uncheck exit time in the transition
the exit time is when the transition is actually allowed to happen
if you have no exit time, you must have at least transition condition (or else you'd always instantly leave the state)
Which can sometimes be useful for organization purposes. I have actually done those sort of blank state transitions just to make the graphs look nicer 😅
is it normal on a project with about 10 scripts that every time i make a tiny change on a script i have to wait almost a minute to finally can click on the play button?
it depends on your PC specs
10 scripts no, either your cpu is very slow or something else is wrong
It's so strange. I have not the best not the worst cpu. It's a AMD Ryzen 7 3700X
I don't get it why it's so extremely slow.
Remember that unless you're using assembly definitions it's recompiling every script. Including ones in any assets you have imported
- AMD Ryzen 7 3700X
- 32 Gig Ram
- M2 SSD
- RTX 2080 Super
yes I mean it was not the fastest when i started the project fresh, but its a very tiny beginner project and the compile time went up like crazy
what troubleshoot steps can i take? I was installing a uncompatible shader a few days ago, which i uninstalled becaues it was for URP
ok I will try 🙂 thx
Hi, I'm trying to modify the colorSeed variable from code to get a random color for certain objects as they're spawned. This does not work, what I am doing wrong here?
25.000 items deleted wtf
you dont have .gitignore for your Library folder?
Nothing here implies git
it is the first projct i tried unity git though 😄
Have you tried manually dialing in values between 1 and 9 to see how it affects the material. It might be that it's not enough to affect the random range node
Yes, it does nothing. I seems to not access the _colorSeed at all.
It looks like just such a small change in the seed is not producing enough variance to cause your Random Range node to roll a different value
Ah, I read that wrong. Changing the colorseed from the inspector works
But it changes the color for all of the objects
Which is not what I want, I want several objects with slight variation in color
I'm not sure how material property blocks work to be honest, but maybe you just need to do renderer.material.setColor? Accessing it will allocate a new material instance which is a bit of a performance hit but that's what you want to be happening anyway since each one should have a different material, right?
because you are changing it
to the original material, which changes it to all objects that has that material assigned
you need to work on a material instance instead
that was it. Now it's back to just a bit slow 😄
thank you very much
worth refreshing it from time to time
Are you sure the properties internal name is _colorSeed in the graph?
is there a way to make a sprite fit with letterboxing/margin instead of stretch or tile?
Supposed to be this?
Removing the underscore does nothing either
Are you sure that code is running at all? What happens if you log rend.material.GetFloat("_colorSeed") after setting it?
If nothing logs, then the code simply isn't running.
🦆
Hello! I need some help
I'm working (for the first time) with a State Manager and States for my objects, and one of them is a gun
Say I have an "Inactive state script" for the gun where the player can't fire it, and an "active state script" where he can. So in the active, I want to give it a prefab of a bullet so it can instantiate it to shoot. However, as only my state manager script is actually atacched to the object, I don't know how to do it because I can't link it in the inspector. What can I do?
You might need to show the code, because I don't see why you cannot link it in the inspector. What's stopping you from just putting a field for the prefab? You could have another script which handles firing, where you plug in the prefab. Then the active state just calls a function on the firing script, it doesnt need to know about the projectile itself
The Object only has attached this script
The script calls classes from others scripts that are the states
i need help. So basically im groundchecking using a layermask array, however i dont know how to set the value of any point in the array. it hard to explain so ill try make is sound easier. my public layermask has two values and for the groundcheck i put layerMask[] but it needs a value inside the square brackets
However if I were to write a variable in the scripts for the states (which are separate) it wouldn't show up on the inspector
1, why an array?
2, set the values in the inspector
Why do you need multiple masks?
bc i have two different layers
So why do you need two different masks
Okay, so they are used in different cases, it's not just a mask that multiple layers are in?
MyLayerMaskArray[] = new LayerMask[] { mask1, mask2 }
Make a field in the current script and then pass the value to the state that needs it. Or do as I said above and make another script to handle firing. Then pass a reference of the new script to your state
If that's the case, and it's just two masks with different uses, I'd just make two fields with descriptive names
Okok
Thank you!
It'd be different if they were supposed to be used in the same place right after each other but it seems like you're going to be using these in different places
im trying to make a button which interacts with physics eg if you throw a box on it or stand on it it pushes down how would i go about doing that?
Which part do you struggle with? Sounds like you know what to do since you described all the steps. Make a button (probably just a cube), uses physics messages to know that something touched it, move it down when touched
i suppose setting it up
i have an idea of how to do it just not familiar with unitys functions
like if i want it to have resistence for example so an object has to be enough weight
I assume you're making a pressure plate sort of thing, it really should be simple enough just using OnCollisionEnter and Exit. I made something similar.
With the weight, you just check that on the rigidbody. On your script that handles all this you can just have a float which you plug in to check what the minimum weight should be
okay thank you
i normally just look for tutorials so i can get an understanding of how to go about it but i couldnt find one for what i was looking for
and for the button to go up and down would i use an animation and swap between the two when something is on it?
Only thing I'd suggest on top of all the obvious stuff is add a timer and a counter. The timer so it does not constantly go between Enter and Exit. And counter so it does not "enter" multiple times
Animation is fine, or you can directly move its position. I initially did animation but it's somewhat weird if you want it fully customizable. Youd need an animation for every case rather than plugging in the numbers directly.
BASICALLY IF U PUT A WHILE COMMAND IN THE WRONG PLACE AND PLAYTEST THE CODE COULD TRY RUNNING FOREVER AND U CAN'T STOP IT WHAT DO I DO I HAVENT SAVED IN 4 HOURS
save more often and turn off caps lock
killing the editor won't make you lose any of your script files
just scene data that you haven't saved
yh ive been mapbuilding
A bit but it still works
Some of the names are probably different now
but there's still a temp scene you can rename to .unity to restore the scene
this one?
That is probably where I would look for backup scenes yes
tysm one more thing tho
basically i want it so my camera plays different music depending on y level; the problem is how do i play it after the musics changed bc i cant put it in the if statement bc it restarts the song every frame
Check if it's not playing before playing anything
how do i do that
how do i have an animation play and stay in the final frame of the animation instead of looping
Disable looping on the animation clip.
unity is messing me up
making a script to disable camera rotation, did this by making a continously updating script that sets the camera z transform rotation to 0 but unity is being very confusing with quaternions
What are you trying to pull with (Quaternion.identity,0f)
basically the idea i have is that my player character rotates
and i have the camera parented to the player character
so when i move it spins the camera as well as the player
i need to freeze the camera's z rotation
The solution to this is just don't have the camera be a child of the player
im also looking into this stuff lately. please ping me if you find a solution
make a script that constantly moves the center of the camera location to the player's location
That doesn't explain that code abomination on the right side of the assignment 😅
Or just use Cinemachine and be done with it
Is it a tuple..? Rotation doesn't take a tuple
heres mine
yeah i did that. not the stop rotation part. im learning the basics of c hashtag now
Read the errors. They basically tell you what is wrong.
I think that particular error was solved a while ago
but both of you should just be using Cinemachine for camera following
yes it was but because im so new to c hashtag i couldnt even follow the instructions or answers given
makes sense
i used that iin2d works well
im not asking for help though. i was just trying to show the guuy that im also looking into thiis stuff lately too
!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.
when i run this code and it collides with something "yes" is not logged and i get a nullRefrence error on line 27---- https://hatebin.com/mpyyemljvi
Then something on that line is null. That's quite a chain of .s on that line so check to make sure they all exist
ok
Can you show a screen shot of the error in the console?
i sent it
how can I make a switch that only executes the code once?
switch (playerState){
case IDLE : {
//PlayAnimation(client.player, idle, false);
client.player.sendMessage(Text.literal("idle"));
break;
}
case WALK :{
//PlayAnimation(client.player, walk, false);
client.player.sendMessage(Text.literal("walk"));
break;
}
}
I got this lil code, and I can't figure out how to do it :(
mmm I got it in an update method
I think I can fix it by "using" the switch every time a change is done rather than leaving it on update method
but either way, it'd surely help me get better at coding, how could I go about it even if the switch is on update?
Switches already only execute the code once
Update runs every frame
Add a bool check that you set to true only when the state changes. Or check if the new state is not the same as previous.
yup yup, but could you help me understanding how to do the bool check? I kind of tried that but I can't figure it out :(
What is there to understand??
if(changed)
{
changed = false;
//Do logic
}
does anyone know how i can make a loading bar for a method? i have a method that generates terrain, i want a loading bar that corresponds with the progress of that.
make the function async
Async in Unity runs on the main thread, and I am assuming there would have to be more logic behind it so it doesn’t lock until it is complete. Something like do X calculations then pause and update the progress bar.
Async runs wherever you tell it to run, and yields however the function yields
there is no magic
Consider using tasks if you need multithreading else async would occur on the thread that it's started - you'd just be able to run asynchronous statements.
https://medium.com/@sonusprocks/async-await-in-c-unity-explained-in-easy-words-571ebb6a9369
https://simsekahmett.medium.com/multithreading-vs-asynchronous-programming-in-net-core-1f1380c4946f
A coroutine could suffice but I'm guessing you've likely already considered that.
Yes, you would generally want to have the work broken down so you can send a callback to the UI
Async doesn’t work the same in Unity mono as it does for .net. Why Unity released all their custom Async stuff
You can still do Task.Run to start a threaded task, you can still switch tasks to other threads
Pretty sure last time I looked into it it doesn’t, but that was a while ago
how do I use transform.position to make one object go to the position of the other one?
For example: I have a Vector3 stored in TPLocation, and I want to make PlayerLocation go to the TPLocation
Pretty sure it was like that at least a few years already(4-5?)
Is playerLocation a vector3 or Transform? If Transform then just PlayerLocation.position = TPLocation;
I have been using Unity for like 13 years now XD
TPLocation = Player.transform.position;
What about GameObjects? The Player being an assigned GameObject, is that how i change its position?
Just do .transform to get the transform from a GameObject
the top line is the code I am using now, and I can see it is somehow wrong, because I use the same structure to assign a value to the TPLocation, but I dont know how to fix it
Afaik in "normal" C# it works the same, if you "just use async" it will continue running on the same thread it was called from
so I'm not sure where this person's assumptions have come from
What I am trying to do:
I have an FPS gun called the Twin Turbos, the Twin Turbos appear in the weapon Holder in each unity scene with the Unity Starter Assets FPS Controller.
I am trying to make the Twin Turbos fire and getting a sprite fire button to work with the gun firing animation in sync.
I want to be able to move while firing.
I am going to send you some scripts that were on the Twin Turbos the way it worked before was the old way in these scripts.
Before the firing button was not working properly, like I could only move and fire at the same time if I presses, and hold the sprite button and move, and if I move and then press the fire button the gun does not fire.
So, can you help me make the Twin Turbos fire while moving? I think the ray cast is done in the scripts I am going to send to you.
The reload that works with these Twin Turbos guns uses a On Click Function.
So, the way I imagine it is, if the player presses the fire button while moving the twin turbos will fire over and over again, so the Twin turbos shoot Animation is playing over and over in the Animation.
If the player presses the fire button for less than a second, at least the Twin Turbo Animation will play at least once (like the left Twin turbos pistol fires and then the right Twin Turbos pistol fires once)
Can someone help me do this on discord screenshare.
Currently the Twin turbos are not firing.
I have tried studying keywords, and functions in C# but no luck.
Using Paste.orCode.org I can send you the whole script easily below.
https://paste.ofcode.org/yUXHvpwqkHCy8gAhPpuUBs This is the **Weapon **script.
https://paste.ofcode.org/WEfdtb4FBRGidcS82khkDp this is the UIManager script.
https://paste.ofcode.org/JpVE3fPRxfPGML2Xdg6V9K This is the PlayerManager script.
https://paste.ofcode.org/jjUDwVnSMaHNUFtKAJVWEm This is the **GameManager **script it may be related.
https://paste.ofcode.org/34i8Zjfv7evzxnndgXcnkky This is WeaponSwitcher script it may be related.
https://paste.ofcode.org/33XETzHvy5ckxUCTrS4nVHF This is the UIVirtualJoystick script is on the Unity Starter Assets Fps Controller, and is a child of the UI_Canvas_StarterAssetInputs_Joysticks
UIVirtualJoystick is designed to handle touch controls for a virtual joystick UI element in Unity.
It allows the player to control movement or other actions by dragging a handle within a defined range.
https://paste.ofcode.org/HCPSmbgfWPBn5iY72uwsc9 This is the FirstPersonController this script is on the Unity Starter Assets Fps Controller.
This FirstPersonController script that handles player movement and camera rotation in a first-person perspective. However, it doesn't include functionality for mobile touch controls, such as virtual joysticks.
Had to do a ton of study on this along time ago, but either got bad results or things changed, glad to see it though
Ah yeah introduced in Unity 2017
is something like this possible? how can I combine two interfaces into one?
Yes you can only have one class inheritance, but many interfaces. Just be warned if you get into generic interfaces if you have multiple like IMyInterface<int> IMyInterface<bool> there will be an issue
how come? so is what I wrote correct?
Does it not work? Is there an error?
you dont really need that IHoverable as an interface
what should I use then?
What you wrote is good yes. The generic situation is because it can’t make sure you aren’t using the same type twice(causing a conflict), but it is Solved by making a sub interfaces aka IMyBool : IMyInterface<bool> and IMyFloat : IMyInterface<float>
Where did the generics come from?😅
you can just have a script with
: MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
and implement the methods you want
Just generally how interface works
i know but if I raycast to check for a component, i wont be able to call the other
so in my mind I should combine them no?
Not sure what you're trying to achieve, but this should compile if you remove the method declarations from your interface.
accidentally deleted a script from assets
any way to get it back?
I clicked cancel on the last second
fuck my life
is it in the recycling bin?
Yeah, that make sense. I combine these specific interfaces too through another interface just to remove the clutter of having my classes implementing the 8+ or so IPointer interfaces when I use them
Other than the recycling bin, you should be using version control; it should not be as easy as accidentally deleting something to lose your project or assets
this is very important, github or plastic are good options
does this code look organized and clean enough or could it be futher worked on? https://paste.ofcode.org/zEc8LNgTmNzkfv9q96FiaT
public int x;
public int X{get{return x;}set{x=value;}}
```no idea why you need property here
i practiced a bit with what getters and setters are used for, and plan to use some more code in those
You can just use auto-propertied instead of making backing fields (like sensitivity)
auto-propertied?
lol what are thooooose
public Vector2 Sensitivity { get; private set; }
No need for the lowercase sensitivity
wait so does it create a variable Vector2 sensitivity or what?
It does behind the scenes automatically (thus the name AUTO property)
it will create a backup field
okay, so using Sensitivity is basically using sensitivity in its place?
you dont need to care its name
okay, i keep thinking of it as a function
property is function
Depends on the use case and the meaning you put into "in its place"
like you would use Sensitivity in your code and not sensitivity?
Yes
but technically it is still a variable its saving to
If it has a setter, yes. That doesn't change the nature of reference vs value types though.
im understanding it a bit more today than yesterday, makin some sense
https://paste.ofcode.org/sBtDCtMHnhzyxcX82AFcAu im gettin some errors only on the left ViewRotation.x -= and ViewRotation.y += It only gave that after i changed the unclean getter and setter to the auto property
It's the same issue as yesterday: you can't modify a field of value type variable returned by a property.
i recognize that, but i dont know how i would fix that
im looking at the error on the web atm
I think I explained that yesterday too.
How do you modify transform.position?
Did you ever try setting transform.positon.x = someValue?
yea i guess
So you address it the same way.
it finds the gameobject correctly, however, it returns the localPosition when using position and not the world space position. any reason why?
use a bool
this is the prefab setup
is the script on pistol or barrel
That's not possible. It must be the world position.
player, left ss is a scriptableobject, right script is on player
"world space position"
ik
oof
thats why its weird
Ah I see. You're getting the transform of the prefab, so of course it would be wrong
whoops
i have a bind on my mouse that types
you have been darkevicted!
should it be the gameobject?
It should be the transform of the instance, not the prefab.
I keep getting this error from Unity when I try to run the game
error CS2012: Cannot open 'D:\Unity Projects\game\Library\Bee\artifacts\1300b0aE.dag\UnityEngine.UI.dll' for writing -- 'The requested operation cannot be performed on a file with a user-mapped section open. : 'D:\Unity Projects\game\Library\Bee\artifacts\1300b0aE.dag\UnityEngine.UI.dll''
did you build your game to the project folder?
I did
ohh try building somewhere else, like desktop
I do not have a desktop unfortunately
Im gettin a bunch of errors on each update frame and also some concerning the same line of code. I cant look around or even debug.log the input in the other class to see what its doing. https://paste.ofcode.org/6L7g4j7DnYHEE7J3ZRwp9v
you dont have a folder Desktop ?
Literally any other folder
Seems very obvious... There's only one thing on line 40 that could be null
The other class is irrelevant
yea, but what am i doin that im not seeing
You never assigned that reference
In fact you made it readonly, ensuring it can never be assigned
Ohhhh so like a new folder to place it?
LOL visual studio suggested i do that, of course its wrong ahha
okay, so i should assign it in start? and remoe the read only?
how do i keep its protection level though?
Usually in Awake
have you saved files to a computer before lol
oh crap i totally forgot about awake vs start and all that
I have lol
Sorry I got confused
i removed private readonly and put public just to test, and put it in the awake method, i got like one less error, but still the same
But i am not sure how to do that if I have all of my projects saved
do what ?
Like I have a folder but its saying that the error CS2012 and how it cant be performed, something like that. I looked for soultions online such as restarting Unity and my laptop but it does not seem to help
did you try saving it to another folder on your computer that is not the project?
How do I save it into another folder other than the one it is saved in? Because when I tried doing that, it would not let me
screenshot where you are trying to do and whats not letting you
Did you actually assign the reference??
That's the main thing you need to do that you didn't do.
Wdym by "put it in the awake method"? Put what there?
yea when that didnt work i put PlayerInputValues = new Vector2(0f, 0f);
and it still said the same thing
{
PlayerInputValues = new Vector2(0f, 0f);
}
You need to assign this reference
You haven't even made an attempt to do so
It's not going to work until you do
i changed it to this public NewInputSystemValues InputValues;
Ok and then... Did you assign it somewhere?
ooohkay i see what ur sayin
how do i check if a value was changed in the last frame?
if (intVal != intVal) {
}
}```
Store the previous value in a separate variable and compare them.
But the better option is just to do the thing as you change the value
how did i not catch that? I guess it didnt register to me that what i was referencing was a script. fsr i thought it was a variable
The variable is the reference
The thing it is referencing is the copy of the script
yes
Do you understand what a reference is?
Think of it like a piece of paper that you can write an address on.
The variable is the piece of paper
The thing it's referencing is the actual house
But your piece of paper was blank. You didn't write an address on it
that makes sense
i got that error solved, but one last error "Rotation quaternions must be unit length". I tried to normalize the line of code but didnt work
What line of code
58
Which is...?
It's because that's getting called before you assign BodyRotation to anything
It's a default Quaternion, which is all zeros
Which isn't a valid Quaternion
fixed gets called before update?
How and When do you get this error
Yes FixedUpdate is before Update
okay
When I was trying to publish
publish?
You should initialize it in Start or Awake
As WebGL Project
are you doing Build and run?
Not at all
ok well i don't have context and id rather not play 20 questions maybe give more info ?
this prob not code related, should in #🌐┃web or #💻┃unity-talk
if i do that wont i need to do that for the other classes that use their variables to make the value of BodyRotation?
What?
I don't know what you mean by that
like i put BodyRotation = Quaternion.Euler(bodyRotationYOnly); which made the error go away, but i figured if you needed to use bodyRotationYOnly as well then ud need to call whatever gets that variable too
also no error codes but my character still cant look around loll probably bc i havent even attatched the camera to it
I mean it's just going to use the initial value of that other variable if you do this
Which is probably a zero vector
i dont know what the right way to go about this is anymore
I don't really know what you're trying to do here, but your code is definitely overcomplicated
haha yes it is
Like why do you have a Vector3 that only stores data in the y component