#💻┃code-beginner
1 messages · Page 2 of 1
think about how you'd change this code to find the image component directly on obj instead of on a child object
you can do it
yes
though if it were me, poersonally
I would replace:
public GameObject InventoryCard; with public Image InventoryCard;
then i can just put in the blank
then your code can just be
Image cardIcon = Instantiate(InventoryCard, CardContent);
cardIcon.sprite = card.cardImage;```
it wont let me instantiate since its not an object
wdym
Image IS an Object
what error are you getting
Severity Code Description Project File Line Suppression State
Error CS0311 The type 'UnityEngine.UIElements.Image' cannot be used as type parameter 'T' in the generic type or method 'Object.Instantiate<T>(T, Transform)'. There is no implicit reference conversion from 'UnityEngine.UIElements.Image' to 'UnityEngine.Object'. Assembly-CSharp D:\Unity\Projects\ClickerGame\Assets\Scripts\CardInventoryManager.cs 30 Active
i copy and pasted
obviously
you imported UnityElements
that's the wrong one
using UnityEngine.UI; is correct
my IDE keeps adding them
you did using UnityEngine.UIElements;
well now i have a new error which is technically one step in hopefully the right way
InvalidCastException: Specified cast is not valid.
(wrapper castclass) System.Object.__castclass_with_cache(object,intptr,intptr)
make sure you reassign the prefab in the inspector
oh wow im slow
i was wrong and it uses sprites not images
so i switched everything over
Sprite cardIcon = Instantiate(InventoryCard, CardContent); cardIcon = card.cardImage;
no?
using UnityEngine;
[CreateAssetMenu]
public class CommonCard : ScriptableObject
{
public int cardID;
public Sprite cardImage;
public int cardRating;
yes
is the actual card
the Image displays the sprite
see here
you have an Image component
it has a field for a sprite in it
the ScriptableObject has a reference to the sprite you want to display in the Image component
it wouldnt lemme put anything on the image for public Image InventoryCard;
this is the thing that goes there
and the sprite is the picture
ohh ok i get it
but why cant i put anything in the public Image InventoryCard; ?
you can
so the cards are duplicating in my inventory when i close and reopen it
im thinking its cause the listitems method is inside when i click the inventory button
well you're instantiating the prefab every time right?
Are you ever destroying them?
A better approach usually is to just reuse the objects
can i just have the prefabs be destroyed when its closed out
I get no errors in the Vs Studio but when i run it in unity i get ArgumentNullException: Value cannot be null.
Parameter name: _unity_self
this is the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Ball : MonoBehaviour
{
public Rigidbody2D rb2d;
public float maxInitialAngle = 0.67f;
public float moveSpeed = 1f;
private void Start()
{
InitialPush();
}
private void InitialPush()
{
Vector2 dir = Vector2.left;
dir.y = Random.Range(-maxInitialAngle, maxInitialAngle);
rb2d.velocity = dir * moveSpeed;
}
private void OnTriggerEnter2D(Collider2D collision)
{
Debug.Log("ladida");
}
}
what line
double click it
and see what line it puts u in
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
and share your full error message @fading slate
not that errors at runtime are normal it just means it's a runtime error, not a compile error.
VS cannot detect runtime errors
hatebin was meant for the code itself but
do u have rigidbody assigned?
this looks like an error in the unity editor/inspector, not in your code @fading slate
man double click the error and show us where it leads u
just print screen it
its okay
sorry i am a bit confused again so i see the error into the console
double click the error
and i double click it but nothing happens
As explained, this error is not from your code
it's from internal unity editor code
double clicking it won't help you
thats what I was trynna see
and it has nothing to do with the script you shared
exactly
ur code is fine
when does the error happen
and how manny of them
maybe make a vid showing?
alright i will make one now, sorry if i dont understand things properly also
it's a UIToolkit error, closing the project and opening it again will fix it
alright i will do this
sometimes just selecting other gameobject on the scene fixes them
it's a serialized property error, which means a rebuild of the AssetDatabase
which close/open will do
guys I need some help again
this error
I thought I had fixed it
foreach(GameObject enemies in enemiesToBeSpawned.Keys)
{
currentNumberOfEnemiesToSpawn = allRooms[CurrentRoomType].NumberOfEnemiesAtATime;
if(currentNumberOfEnemiesToSpawn > 0)
{
while(enemiesToBeSpawned[enemies] > 0 && currentNumberOfEnemiesToSpawn > 0)
{
GameObject colliderCheck = Instantiate(Spawner, roomPos + new Vector2(Random.Range(-rooms.Point.x, rooms.Point.x), Random.Range(-rooms.Point.y, rooms.Point.y)), Quaternion.identity);
ColliderCheck colliderStats = colliderCheck.GetComponent<ColliderCheck>();
colliderStats.enemyType = enemies.GetComponent<EnemyHealth>().EnemyType + 1;
colliderStats.enemy = enemies;
enemiesToBeSpawned[enemies] -= 1;
currentNumberOfEnemiesToSpawn -= 1;
}
if(enemiesToBeSpawned[enemies] == 0)
{
EnemiesToBeDeleted.Add(enemies);
}
}
}
in this foreach
Cant I change and item in a foreach
using a dic
yes you can but you need to use KeyValuePair not .Keys
foreach(GameObject enemies in enemiesToBeSpawned.KeyValuePair)
this?
I cant change it
no
where
foreach(KeyValuePair<GameObject,int> enemies in enemiesToBeSpawned)
then you can use enemies.Key for the GameObject
and enemies.Value for the int
I dont quite understand it
woah, wait, that's not gonna work because the int in enemies.Value is not the same int as in the dictionary
A KeyValuePair is one entry from the dictionary
with both the Key and the Value
Has anyone ripped this shills base code and uploaded it to the dark web yet? Asking for comrades…
Not a beginner coding concept of Unity I'm afraid
@uncut dune Try this
using System.Linq;
...
Dictionary<GameObject, int> gos = new Dictionary<GameObject, int>();
gos.Add(gameObject, 0);
...
foreach (GameObject go in gos.Keys.ToArray()) {
gos[go]++;
}
Debug.Log(gos[gameObject]);
ok thank you
Hey guys, i have a window gameobject. I wanna like rotate freely, example, moving the Z-Axis of the window from current position to value 74 smoothly. How do i do it? I have this code but this is not moving smoothly.
windows[0].GetComponent<Rigidbody>().transform.localRotation = Quaternion.Lerp(Quaternion.Euler(0, 0, -64f), Quaternion.Euler(0, 0, 74f), timeCount);
timeCount += Time.deltaTime * 0.22f;
presumably that code is in a Coroutine
It is in Update 🙂
post the complete Update method, a screen shot will do
Here you go
Have you tried Slerp instead of Lerp?
Lemme try slerp one sec
Tried
Still the same
Can you make a vid of whats happening, your code looks fine, a bit odd but it should work ok
Must i added anything? Like physics or something?
no
what you have is almost identical to the
https://docs.unity3d.com/ScriptReference/Quaternion.Slerp.html
show the inspector of the object you are rotating
@languid spire Here you go
Floor to int will always return 0
i want the score to just constantly keep increasing
Look at your FloorToInt call it can only result in 0
Sorry, should have seen this before, you have a RigidBody so you cannot rotate by changing transform.localRotation
you are combining manual and physics, a no-no
i dont wanna add this check for everytime i press an input 🥹
I've given you your answer!
So if i remove Rigidbody, what should i change ?
this?
.localRotation to .rotation?
well, obviouisle the GetComponent, which you did not need anyway
yes
windows[0].transform.localRotation = Quaternion.Slerp(Quaternion.Euler(0, 0, -64f), Quaternion.Euler(0, 0, 74f), timeCount);
I've removed rigidboyd and changed to this. Still doesnt work
define 'doesn't work' exactly
Um, its rotating but i wont gradually stop
It will be like stop to the 74 in a sudden
like this?
score += (scoreIncreaseRate * Time.deltaTime);
still wont work
why are u making a coroutine tho?
couldnt u just do it in start method
or maybe instead of using a loop just put it in update
i want the score to just constantly keep increasing
so it will update every frame
so everyframe?
My bad, i did say smoothly. Perhaps i forgot to say about gradually stop 😅 So now, i want to ask how do i make it stop gradually?
just make score a float instead of an int
yes
exaclty
can u paste the code here and I'll show u what I would do?
sure
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class ScoreManager : MonoBehaviour
{
public TextMeshProUGUI scoreText;
int score = 0;
public static ScoreManager instance;
// Rate at which the score increases per second
public float scoreIncreaseRate = 1.0f;
// Start is called before the first frame update
void Start()
{
scoreText.text = score.ToString() + " POINTS";
// Start the score increase coroutine
StartCoroutine(IncreaseScoreOverTime());
}
// Coroutine to increase the score over time
IEnumerator IncreaseScoreOverTime()
{
while (true) // Infinite loop to keep increasing the score
{
// Increment the score based on the rate and time elapsed
score += Mathf.FloorToInt(scoreIncreaseRate * Time.deltaTime);
scoreText.text = score.ToString() + " POINTS";
yield return null; // Wait for the next frame
}
}
}
Ok, you are multiplying by 0.22f, you need to increase this as the Slerp progresses so that it slows down
void Update()
{
score += scoreIncreaseRate * Time.deltaTime;
scoreText.text = score.ToString("00") + " POINTS";
}
also score should be float
so
float score = 0;
Hmm, its not possible rotate it at a slow speed, and then gradually stop?
can simebody explain to me how to make movemnt for players in 2d platformers
of course, like I said
hello?
Hmm.. okay.
timeCount += Time.deltaTime;
``` i changed to this. Its moving as it is but it won't stop gradually. Not sure if its my code or im doing something wrong
you are not thinking or looking at what I said
You want someone to explain movement? can't you just google it ..
float step = 0.22f;
void Update()
{
transform.rotation = Quaternion.Slerp(from.rotation, to.rotation, timeCount);
timeCount = timeCount + Time.deltaTime*step;
if (timeCount > 0.5f) // After halfway
step += 0.05f; //slow down
}
as step gets bigger so the rotation slows down
This is working. Thank you so much for helping! Appreciate it
🙏
is there a builtin HexToCOlor method?
that's what im using too, but it is quite ugly to write for me
imma write my own that just return a color ig
Hi everyone 👋 - I am wondering what is the correct way of building a menu system for a game - is it to have a 'scene' for each step in the setup of a game? And is this best to build entirely with UI Builder? Thanks in advance
UI builder! Sounds like a cool stuff i cant have 🥹
you are missing nothing, it's so full of bugs as to be virtually unusable out of the box
save me the stress ig, knowing me, id force it to work even though i have other ways to solve a problem
Even Unity can't get it to work correctly, hence all the Editor UIToolkit errors we keep seeing people posting
oh i see, so it was also the UI toolkit, yea im quite aware how frequent someone got problems with it 
How to name the base class for Projectile and Laser?
open another scene
WeaponEffect ?
thanks
Nah
It's better than CouldBeAnythingThatComesOutOfTheEndOfAWeaponWhenFired
that sounds better
If you think that you have a lot to learn
im trying to draw ray and freezing time to see why the hell it misses the thing I click on if planet itself is moving but ray clearly intersects box collider first before sphere one so now im confused https://hatebin.com/zbtorzaukh
oh my god this switch lol
so do you not want to hit the box ?
That Debug.Log appears to be coming from MouseInput not ClickedOnScreen
The MouseInput code you posted does not have a Debug.Log
whats up with switch and ye if it hits box collider u see in vid it would print BuildingSlotRoot name
but it prints earthroot in console u can see
that should happen if that ray hits sphere collider on earth only
is the white box a collider ?
those siizes looksus
into its own method but its same stuff
white box is bounding box I think unrelated
actually nvm let me see wtf is that white box lol
oh
thats ui
well a box collider gizmos is green
so where is the box collider at
can you show the gizmos for the box collider
btw if you wanna pause to debug is better to use
Debug.Break() than timescale (it doesn't effect other scripts from executing)
didnt knew ty
and combined with earth sphere collider
it extrudes and ray intersects it
are you sure its staying in place in playmode
relative to earth yea
is there any teenagers that want to talk about coding with me im 13
and i want to lurn how to code
its kinda off topic tho im more interested in maybe my ray draw is just wrong cause how can it just ignore my collider
I need to compensate click to the side to actually hit it lol
check pins for courses
gizmos rays don't care about colliders
yes but it doesn't stop at colliders
ok ty
yea so u see
I have the real ray running in that code I posted yes
and just after that I draw a line using that ray origin and its direction
so I can just assume my real ray is going through exactly that line
you should draw the ray from Ray.origin to rayhit.point
aa lemme see
believe that would be a Debug.DrawLine
pins?
if its not hitting the square, the collider might be moving (maybe you have non-uniform scale somewhere and rotating skewed)
@ashen ferry
mhm
ok
yea so my ray bro actually just hits air 
i couldnt find anything
do you know how
Look under Resources in the pinned messages
yeah thats wierd..
what is scale Root Planet or w/e is called
1 its quite nested with varying scales tho but wtf do I do if that matters
theres no apply transforms or anything like in blender
it only matters if the scales are non-uniform
it causes skewing on rotation
eg of non-uniform
0.3 | 0.2 | 0.3
oh nah
its aight tho nevermind one of those bugs where im getting cancer trying to figure out and 2 days later it will be something incredibly simple
fair enough , def keep an eye on collider gizmos while in playmode just in case
GameObject prefab = Resources.Load<GameObject>("Prefabs/PlayerPrefab");
player = Instantiate(prefab);
```this gives me "the object you are trying to instantiate is null but there is a prefab named "PlayerPrefab" on the assets/prefabs folder
I suggest you read this
thank you
Hey guys, I'm having some trouble with trying to solve fast diagonal movement with an analogue stick
The solution I'm seeing online is:
if (input.magnitude > 1)
input.Normalize();
or using Vector3.ClampMagnitude
This works well with keeping my character from going over the speed limit that I've set, but if I try to adjust the input factor and pass in 0.5,0.5 the diagonal magnitude will still be around 0.7 and it moves faster diagonally because of this
I can't just normalise the input always because the magnitude then clamps to 0 or 1
Any help would be appreciated, thanks. I seem to be missing something, as everyone online is happy with the initial solution but I'm still having issues
I need Friends really badly and i want to make a game so im 13 my name is Christopher and I use unity if you want to make a game with me reply
!collab might be of help as I doubt many people are seeking for a collab in #💻┃code-beginner. If anywhere here then probably #💻┃unity-talk. For the friends part, can't really help, unless you want to be my friend🙂
man why the commands never work for me
!collab
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
there we go
Hi, I want my 2d sprite to rotate to face left, up, right, down through code, but I don't want to learn quaternions for that, which parameter do I need to change to control the rotation on the Z axis?
no need for quaternion, use Euler angles
or you can multiply the Quaternion by the Vector3 of the direction you want
What's the difference?
Euler is easier to work with using Vector3, Quaternion struct has a method for it.
how to store list of lists
it enforces every list to be of same type but i want different types
you probably need dictionary
List<List<object>>
dont i need convert types then?
object can hold any variable
Can't really do much with it other than just pass the reference around though
o right
you could even do
List<object>
and just fill is with anything you want
how can i take the point of a raycast even if it didn't hit anything
origin + origin.normalized * distance
didn't get it
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity))
{
Vector3 pos = hit.point - transform.position;
transform.rotation = Quaternion.LookRotation(new Vector3(pos.x, 0, pos.z), Vector3.up);
}```in my case how do i implement it
in your case you dont
whats the legit use case for List<List<object>> if fr like wut
to store multiple Lists of different types
but i pauses and it dose not looks at the mouse if it dose not hit anyting
yea and what u gonna do when u want to do something with certain list
you cast it back to it's original type
you are using Infinity, you cannot have a point at infinity
int directions[] = Board.Squares[i].pieceColor == Piece.LightColor ? new int[] { 7, 8, 9 } : new int[] { -7, -8, -9 };
cannot convert from type int[] to int
used this exact line of code in another project and it was working, whats the problem here
is it cuz im using a newer version of c# or smt
Exact?
int [] directions
I can only throw properly on the first time, on second and other they stop on air and start moving towards me(when frozen is true I mean)
https://hatebin.com/zqjhvdwzst
https://hatebin.com/pthyeajute
https://hatebin.com/iraptufcto
whats the best way to rotate a quaternion on one axis without having to change any of the other values? orientation.rotation = Quaternion.AngleAxis(yRotation, orientation.up);This is what I have so far but it's just causing my capsule to spin violently
This is for a camera script, I will post the full script if asked
how to find the component of an inactive object with a tag?
MyComponeont myComponeont = FindObjectOfType<MyComponeont>(true)
but
the there is already
other gameobjects with the same component
I want one with a specific tag
I cant do that
cuz that would be calling the gameobject wouldnt it
yes
why is the object disabled?
just disable the components
this way you can use Tag find
it is a slider
I cant just
disable the slider component cuz the object would be still showing
then put it inside a gameObject with tag you don't disable ?
Are either of the objects involved here prefabs
good idea
no, only the object that is getting them
So drag in the reference directly
I cant drag to a prefab
That's why I asked if either of them were prefabs and you said no
I said only the object that is getting them
In that case, have the thing that spawns the prefab with a reference that you drag in, and then set the variable after you spawn the prefab
good idea
Hello, I am currently trying to make enemy pathfinding for my game. I have a basic navmesh system working, but I wanted to make it better with a "predictive" system. I followed a Llama Academy tutorial for creating such a system, but when I attempt to run it I recieve an AABB error.
Heres my code:
https://pastebin.com/f3tfMSvU
Here's the tutorial:
video https://www.youtube.com/watch?v=1Jkg8cKLsC0
github repo https://github.com/llamacademy/ai-series-part-44/blob/3779343025f1b5218d35b40427a2adc74eae8f69/Assets/Scripts/AI/EnemyMovement.cs#L4
Here's a screenshot of my errors:
I should note that when I just run: agent.SetDestination(victim.transform.position); there are no errors and the pathing works just fine.
victim referring to a class put onto the player (or any desired G.O.)
said victim class also runs a script called PosSpy shown in the pastebin below;
https://pastebin.com/UyRyVFiT
make sure whatever is inside setdestination is a vector3
make targetpos
a Transform
and then pass the transform
targetPos = victim.transform;
like this
agent.SetDestination(targetPos.position);
try this
Ive had a similar problem and this solved it but Im not sure why was it, maybe someone else can answer
the only thing is that targetPos already seems to be a Vector3
Vector3 targetDirection = (targetPos - transform.position).normalized;
Vector3 playerDirection = (victim.transform.position - transform.position).normalized;
float dot = Vector3.Dot(playerDirection, targetDirection);
if(dot < PredictionThreshold) {
targetPos = victim.transform.position;
}
agent.SetDestination(targetPos);```
since it is defined as a vector3 type, the script wouldn't compile if it didn't contain a vector3 value
if I try to define targetPos as a Transform, then the original definition for targetPos does not work, since you are passing in a Vector3 at the start.
Hey, guys!
All very well?
I recently started learning Unity and I'm trying to make a jump function using the Input System
But I'm having problems, I reviewed the code and input mapping, but it doesn't work, can anyone help me please?
private void OnEnable()
{
playerActionsAsset.Player.Jump.started += DoJump;
move = playerActionsAsset.Player.Move;
playerActionsAsset.Player.Enable();
}
private void OnDisable()
{
playerActionsAsset.Player.Jump.started -= DoJump;
playerActionsAsset.Player.Disable();
}
private void DoJump(InputAction.CallbackContext obj)
{
if(IsGrounded())
{
forceDirection += Vector3.up * jumpForce;
}
}
private bool IsGrounded()
{
Ray ray = new Ray(this.transform.position + Vector3.up * 0.25f, Vector3.down);
if (Physics.Raycast(ray, out RaycastHit hit, 0.3f))
return true;
else
return false;
}
why am i getting an error when trying to compare a Color32 with another Color32 using ==
nvm i just used Equals() instead
You'd have to say what the error was
Hey, I made it so when an enemy collides with player the enemy attacks the player and it works. But I want the enemy to attack the player multiple times instead of just once. Im using the oncollisionenter2d. How would i go about to make that happen?
This is in 2D btw
Hi I'm currently trying to make a game with similar mechanics to pokemon. Would it be okay to ask for help in this channel or would it be better in some other channel/thread?
is it about code?
Mostly about code, and maybe how to attach them to the game objects in unity
All the script says is that if enemy collides with player then it damages the player.
ask your question
OnTriggerStay maybe? or a Physics.overlap, with timer
Can i use the oncollisionstay?
Im not on pc so I cant check if that works or not
sure but you're only dealing with the outer edges when using Collision instead of trigger
so they should always make contact
ooo
Okay I'll try the trigger thingy tomorrow and hope it will work, another question is if i want it to deal damage every like 1 sec or 0.5s how do i do that
using a bool condition + timer in Update
or Better way is using a simple Coroutine
👍 alright, thank you
I'm currently trying to transition between the overworld (where the player moves the character and interacts with npcs), and the conversation (which is the battle in pokemon) on the condition that the player presses the interact button while colliding with an npc. So far when the player interacts with the npc, a dialogue box appears. Then I'd like to move back from the conversation to the overworld when they pick the last correct option.
So question is how to make those two transitions? any help is appreciated
An option would simply have the Convo part to be done in UI
show a dialogue gameobject you can change dynamically, depending the npc or w/e
the convo part is a multiple choice with a button that does something different for each choice, would that still apply?
yeahh
you can re-use the same button for different method/scripts passing the reference around,
Adding/Removing 'listeners'
hmm sorry im a complete beginner, could you explain further on how to do that?
I have an issue. Say I need different tutorial images for a different scene. If the player is still holding down a key from the previous scene (because my game doesn't need any loading screens, so that is bound to happen), the tutorial is skipped as the game detects a keypress and thinks the player pressed a key. How can I circumvent that?
maybe a timer / "cooloff" period
Do you think I'd be able to ignore the input all entirely? Or is a cooldown the best solution?
You would keep for example 3 buttons referenced in 1 main script you can access any time and map different methods to those buttons and listen for clicks.
Learning how UnityEvent works would help you here
thanks for the help, ill try to figure that out
you could, how do you want your inputs ignored ?
I want to check to see if the player is holding a key one the first frame and ignore that key entirely until they stop pressing it and press it again/a different one
maybe store the key inside a variable and use that inside a check ? psuedo : if press anykey and is not storedVariableKeycode
or just if(Input.anyKeyDown && !Input.GetKeyDown(myKeyCodeVar)) //do stuff;
kinda ugly tho might create other issues, probably better to approach what you're doing differently
Help, Unity crashes when switching from game to scene view (randomly).
I'm on Windows, using AMD ryzen 9, Radeon RX 6950
a fatal error in the mono runtime or one of the native libraries
used by your application.```
I think this isn't the right channel for this. Maybe unity talk
My b, thanks!
does anybody know how to fix this?
I literally haven't touched my project since last time and it was working fine
just woke up to this
Press clear?
How does that fix the error
Unless you've done something this could be a false positive and clear or resetting the editor may quickly fix.
Nope, there's definitely an error
Currently its causing my game object in my inspector to look like this
Well, it's got to do with reflection and the mesh simplification controller, good luck.
Lovely
operator “==“ can not be applied to operands of type “Color32” and “Color32”
Make sure they're the same type - could be referring to Unity's and another.
Or maybe color 32 doesn't have an overload for the equality operator
Believe it or not it seems to be the latter https://github.com/Unity-Technologies/UnityCsReference/blob/94bcde1a7e8af4cc3212d756bf59632b979517f2/Runtime/Export/Math/Color32.cs#L59
Hi guys, i have a question on rotation. I have an object where i am rotating the Z axis. How do i have the mid point or 75% of the arc/rotation marked as ?? I'll be glad if anyone can help me out. Thank you 🙏
I am using values.
Example A val = 255, B val = 50
iirc Lerp could do it , and u can pass in 0.75f
i used lerp, but lerp will choose the shortest route
sorry, you mean, quaternion lerp?
I am unsure how you don't get the shorter angle, there must be some third variable to indicate why you want that particular direction
im attempting to trying to produce a cube on a specific face of another, then again on the cube created in the first action. does anyone have any ideas?
with the new starting point always being the end of the most recent iteration, the length and thickness always being the same based on the text put in the given field, and the number of iterations based on the number of letters
it feels very complicated, and im sorry to ask so much
Weird.. its not suppose to look for nearest path?
Quaternions are always interpolate the shortest part. Math.LerpAngle is designed to do the shortest lerp in euler angles (0->360), and normal Math.Lerp just interpolates between two numbers, and knows nothing about context
I see
anyway, why is it returning in decimal when i do this Debug.Log(gameObject.transform.rotation.z);? Is it in radian?
ok tq
Why is my gameobject transform rotation Z in inspector shows -49.427 but when i Debug.Log("Rotation " + transform.localRotation.eulerAngles.z);, it gives a different value such as 310.57? Am i doing something wrong?
Read the note on that very page
i am using euerAngles
Yes, I understand
The note is talking about angles read in code differing from those in the inspector
and what i dont get it is, inspector is giving different value as what i debug
Did you read the note?
yes
Then what's confusing about it? The inspector values are user authored. The values returned from eulerAngles are derived, and go through a transformation
When scene as a complete rotation with all angles, the result is the same
but individual angles are meaningless without the full context of the rotation
Okay, so i believe we need to go for the ones in the code itself since it is more accurate ?
They're both the same angle interpreted differently
Depends completely on your implementation, I give suggestions in the note
noted
Alright thanks guys 🙂
tryna work with the new input system, got this
Assets\Scripts\MouseManager.cs(118,25): error CS0246: The type or namespace name 'InputAction' could not be found (are you missing a using directive or an assembly reference?)
the void with the error:
private void OnLook(InputAction.CallbackContext ctx)
{
if (ctx.performed)
{
_input = ctx.ReadValue<Vector2>();
_isGamepad = ctx.control.device is Gamepad;
}
}```
are you missing a using directive or an assembly reference?
I understand that. Am I supposed to have some reference there?
like Using UnityEngine.something
Do you understand it though 🤔
some reference is missing. But I'm asking, what reference is missing
use the quick actions in your IDE to add the correct using directive like vertx's link shows
k works now
https://gdl.space/murosubebe.cpp
I wrote this is code as a system to equip different skins inside my game, but the value isnt being saved across playthroughs
Anyone know why
you're not actually using the value you get from PlayerPrefs. you call PlayerPrefs.GetInt but don't store the value anywhere
doesnt player prefs set int store the value?
i mean store it in your code to use in your code. GetInt returns the int, but you don't put that returned int into a variable
letsgo it worked thx
Guys, How to destroy a gameobject when it is triggered?
Destroy(gameObject)
Simple as that ?
that likely will not be what you want to do exactly but 🤷♂️ you havent really described what you're doing
Not working
the coin should disappear when the player hits it
what have you done to make sure that OnTriggerEnter is actually being called?
can we add another option here ?
Oh my god,
wait a sec
Should I place the function in "Update"?
no @vestal valve
Then?
I suggest you answer @slender nymph question
check a few things
- Your gameobject has a collider set to trigger
- you have that script attached to the said gameobject
- you have Destroy(gameobject)
- edit: check if you have rigidbody on gameobject
If this still doesn't work I suggest you show a example / screenshot of what you've done
Easier for us to help
I'm sorry but I don't understand.
I thought this code will apply when any gameobject triggers it, and it executes the code
and again, what have you done to make sure it is actually being called?
have you tried any debug.logs? have you used breakpoints? or have you done nothing and already run out of ideas?
I'm sorry, there was no mistake in coding, its my eyes, I just checked for "is trigger" toggle.
But never looked out the "collider"
Happens man, good stuff that you figured it out!
hello, I want to create a platform system where I can specify the number of instructions the platform needs to make, and them configure and set each one from the editor w start/stop time, also the action between rotation or movement.
how do I get the editor to update dynamically with the number of instructions so I can set all of them (without adding a different script on top and modifying that one)
I was thinking of making the basic movements and their configuration and then having a manager script specify the script count for each platform and then configure them from there
So uhhh, I just started with code, went to edit it, and I need to open it with something, is there a specific application I can use that's made for this stuff?
yeah, visual studio
or visual studio code
Thank you!
I use visual studio
make sure you configure it too !IDE 👇
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
🫡 real men use notepad
it's good
I only use it for small scripted games on a computer
I mean it's the best I could do on my school computer
oh
can i change what way a slider fills. i.e would like the start to be top right
I've never used sliders like that but wouldn't simply rotating it work ?
Or scaling it negatively if you want to "mirror" it
thanks i used rotation. thought maybe it had the option built in the component
hey a quick question
If I use "Instantiate", The game object gets spawned once. Is there any shortcut to spawn multiple times or Should I type the code again.
(Excluding the loop functions)
(Well again I'm not sure, maybe there is, I've never used it 😉
But if rotation works, I guess you don't need to look further 🤷 )
use a loop
ok
Hi. I am trying to find a way to add +1 to my battery counter when i collect a battery. I cant figure it out in a clean way of code. I've managed to get it to work by making a separate script that has a void start +1 that will enable once i collect the battery hence giving me +1 but i really dont like this method. any help please
so you know how you've got that interaction event? you can create a method on the desired class that you call from the interaction event and that can increase the count by 1
I played around with that for hours and could not get it to work.
i assume I add the flashlight script to it since that holds the value of batteries, then what. thats where i get lost
then you can create a method on the desired class that you call from the interaction event and that can increase the count by 1
i saved my code then this somehow appeared
that's a build error. if you weren't trying to build then clear the console and move on
you can even restart the editor if it bothers you that much
it doesnt let me start bcs of error and it keeps appearing
i wasnt
Would you mind helping me with that? Is it something I need to add via code or can it be done from the interaction event?
both . . .
surely you know what a method is, yes?
update/start etc right?
its not working
Update, Start, etc are examples of methods. those are sort of magic ones though since unity calls them automatically
how descriptive. i definitely know what is going on with such a great description of the issue!
It is not going away. ive done nothing. if i had the description of the problem sir, i would have solved it myself.
did you restart the editor?
How to use "and" function in C#
Does "and", "or" exists ?
yes.
assuming you are referring to logical operators
well it's not an issue with the code because it isn't a compile error
So I'd make a new method, and then call upon that method I made to increase it by 1 when I press my interaction button
yes
gotcha. Thank you. Makes sense now
I know, but i was trying something then i went into unity to test it and it said this
okay well this is a code channel
in a scene i could somehow not save it bcs acces was refused
ok where do i ask this then
perhaps your install is fucked. or you may need to delete your Library folder. i have no idea, i'm just a programmer
bcs acces was refused
well that sounds like an OS permissions issue
\x11LLL\x00\x07\x01\x02\x01\x00\x10\x9f\x9d\xa7C\x01
it kinda seems like hex
but dunno how to decode
nice help, thanjs
Maybe asci? Cannot be hex with L
its binary as far
requires some processing which i am unaware of
tho its a string representing hex
I have absolutely no clue what you mean by that
Where did you get that string from and what're you trying to do with it?
That isnt binary, and L isnt hex
was thinking the same
the final result should be a base64 string
and converting it to a normal utf-16 string it returns offline/online
Seems like an ascii escape character for byte
idk much
was here to know what exactly it is
Wut.. u initially said its binary and hex after I suggested ascii
.
ascii is utf-16
its a possibility if the final string is utf-8
all i need to know is what is this thing even i dont know myself
\x11LLL\x00\x07\x01\x02\x01\x00\x10\x9f\x9d\xa7C\x01
its not that advanced to be moved in higher channels
that's a link to a message in this channel, mate
read and answer the question
It's not programming
sad
probably intentionally ignoring the question because it isn't remotely unity related
websocket API
for unity
that might explain
I am doing side by side tests with python as well
Where do i ask this problem then if not here
well that certainly doesn't actually answer the question that was asked
#💻┃unity-talk is a catch all channel for questions not related to other channels
using System;
using UnityEngine;
using UnityEngine.EventSystems;
public abstract class PlayerButton : MonoBehaviour, IPointerDownHandler, IPointerUpHandler {
[SerializeField]
public GameObject player = null;
public bool held { get; private set; } = false;
public void OnPointerDown(PointerEventData eventData) {
OnPress();
Debug.Log("press");
held = true;
}
public void OnPointerUp(PointerEventData eventData) {
Debug.Log("release");
OnRelease();
held = false;
}
public void Update() {
Debug.Log("frame");
if (held) {
OnHeld();
}
}
public abstract void OnPress();
public abstract void OnRelease();
public abstract void OnHeld();
}
Update just doesnt get called somehow OnPointerUp & OnPointerDown logs but it doesnt log "frame"
does the inheriting class happen to have its own Update method?
for anyone that may be seeing this and wants to know how to fix it: mark the base class's Update method as virtual and override in child classes and call base.Update in those overriden methods
Does anyone know why camera spawns at foot level?
obligatory "use cinemachine"
Which gameobject are you following?
You might be following the character model's pivot point
I would usually use a separate look at point that is positioned at character model head.
yeah
i can only put pivot on center
not like in the head
Try creating a empty gameobject on the character, then position it on the head.
ok
And then have the script follow the empty gameobject
But like boxfriend said, I recommend cinemachine too hahahaha
idk how to use lol
fix it with this
can i implement the cinemachine in a start project?
What you mean by start project?
Oh you mean beginner project? Yeah sure of course you can
There's a whole unity tutorial on how to use Cinemachine
but if since you already have a camera script you might as well continue unless you are interested in cinemachine
How to move a gameobject left and right continuously ?
The code I wrote is not working.
few things to check,
- have you attached the script to the gameobject?
- is the value moving at all in debug view?
Use an if statement, not a while loop
Update is a loop that is executed every frame
Your loop completes in one frame, teleporting the object
Also .x will never equal 5 exactly
You can use their approach https://discussions.unity.com/t/help-how-to-move-an-object-left-and-righ-looping/111582/2
I was going to close this question as a duplicate since similar questions have been asked and answered in the last couple of years, but in a few minutes of Googling I did not find a good fit for an answer to point you to. So here is a new answer. Whenever you have something that is cycling back and forth, whether it is position, rotation, colo...
Can someone help me out. How do I make an object to snap to the terrain during run time? For some reason, the object is half under the terrain.
I would think it's something to do with your gameobject's pivot point.
it is just a basic cube
Yeah then the basic cube's pivot point is in the middle I believe
Maybe your offset is wrong
Uhh another gameobject to hold the prefab, adjust the position, then make it a prefab
Why is he flying? lol
@lilac hemlock
code
thanks, but isn't there an automaric solution
with a cube it is okay
but it seems a lot of manual work for more complex models
If your complex model's pivot is at the bottom, then this issue shouldn't happen
Question, is the character falling when it gets to that height or it is a fixed position kind of thing (like just in mid-air, zero movement)
Or rather, does your character have rigidbody and a collider?
I'm assuming you do cos there's charactercontroller
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Lives : MonoBehaviour
{
public RawImage image1 ;
public RawImage image2 ;
public RawImage image3 ;
public static Lives instance;
private int flag = 3;
private void Awake()
{
instance = this;
}
// Start is called before the first frame update
void Start()
{
image1.enabled = true;
image2.enabled = true;
image3.enabled = true;
}
// Update is called once per frame
public void Remove()
{
if(flag == 3){
image3.enabled = false;
flag--;
}
else if(flag == 2){
image2.enabled = false;
flag--;
}
else if(flag == 1){
image1.enabled = false;
flag = 3;
}
}
public void Enable(){
image1.enabled = true;
image2.enabled = true;
image3.enabled = true;
}
}
okay, thanks
did you forget to drag RawImage objects into the slots in the inspector?
yes
well either you have more than one instance of this object in the scene, or you are not correct
When I enter playmode it's on the ground but as soon as I press "W" it goes up and walks
Try adding that first?
only this
yeah i used multiple refrences in the objectmovement script
to call different functions of this script
If i change the height here he go down and up, maybe is this?
huh? i'm talking about multiple different Lives components in your scene
this is the moving script and i called lives here many times
okay, that's entirely irrelevant to what i've said
is this u r talking abt?
oh sry, i didnt udertand 😅
oh now i understand!!!!!!!
u were right
i copied the canvas multiple times for diferent purposes
but didnt remove the script
😓
working fine now👍
idk why
neither do we
whenever u post a question make sure to give some resource to it, we cant blindly guess because there is sooo soo many things that can go wrong
Show us the character gameobject, where you put the script
Thanks for this
try reducing ur skin width in character controller for start
make sure ur animations dont control your Y position
if those 2 didnt fix it, then you will have to show us your script for movement
^he showed us the script already 👍
also make sure ur box collider isnt oversized
don't work
show us the gizmos
while in play mode
go to analysis, physics debugger and show those gizmos
@left star I think it's this situation
maybe this one
yeah
also in your code u set Y to 0
check before you start your game, what is your Y
if its -something
then thats why it goes up
Yeap, adjust your character controller's position, height and stuff.
these 3 things
i think is the radius
Make sure it looks like something like this
Question, would an attempt to call .SetActive(true) on a GameObject which is already active, cause to call OnTriggerEnter2D again for anything already within the trigger radius?
yeah done
thxxx
now I think I need to add gravity? bc if I go over something, the character flies again
I don't think so. Plus why do you need to call SetActive(true) when already active?
Yeap. Rigidbody and stuff.
I don't need to. Asking since I'm working in a team and there's a weird error involving triggers, and I though that this might be one of the possibilities as this does happen there
Ah I see. I thought it was weird. It shouldn't affect it tho
Basically the attack range is done badly and is set to active each frame
An entity once calling Destroy, exits the trigger twice, then re-enters it and OnDestroy get's called after that
i believe so, but you could manipulate the collider to still stay disabled , raycast distance and enable when its out of colliders reach
or create a different collider in child that will have ontriggerexit to enable the trigger in parent
Well, I only needed to know if OnTriggerEnter2D would be called again by doing so, as for the solution I'll just beat my team members until they change it so that .SetActive(true) won't be called each frame, so there's no need for anything fancy like that
why dont you use the debugger and find out for yourself?
I did debug it and it seemed like the case, that's why I asked this specific question just to make sure that I'm not actually dumb
well you can still reccoment them these ways to do so
just make sure u wear gloves, they aint worth bruises on ur hands
I did send these to them, just in this case it won't be necessary
Heyo, had a question. I've got a simple moving char, no mesh so no footstep animation. Getting a lot of diff ways to go about. What would be a good suggested way player simple walk around the house to play footsteps correctly? Would be same floor etc, could expand on that later, just want core down.
I was dabbling with the players velocity and I wasn't sure if just to use a timer or
Would be first person (why no mesh) and the player would stay at the same speed ideally walking around.
good afternoon friends, how do I Physics2D.Raycast diagonally? https://hastebin.com/share/iyihuxepez.csharp i've tried the following: var right = transform.TransformDirection(Vector3(1,-1,0)); for a diagonally right down angle but i dont think i'm doing it right
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Best to lookup tutorials to see what fits your needs best.
Here's a random YouTube example that seems friendly enough: https://youtu.be/ELz_EG-s0jU?feature=shared
Learn the basics of moving objects in Unity as well as a few different approaches to fit your game needs.
First, you'll learn how to directly change the transform position of your object. Then I'll show you how to move your character using Unity's physics engine so you can correctly collide with other objects.
=========
PlayerController.cs: h...
Maybe I wasn't clear, no issue with player movement. Talkin about audio for footsteps, without using animation events.
Did you try Googling? 
Was just about to suggest that but okay. A timer would work too, depending on the level of need for accuracy.
no need to be rude. I get a lot of people come here for the answer instead of looking up. I would not be one of those
why not simple if(!IsPlaying) ?
you mean like a player IsMoving(Play Sound)?
no i mean just have if(!yourclip.IsPlaying) {yourclip.Play();} in your movement script
I wasn't being rude and you're misinterpreting text. These code channels usually discuss coding implementations. As is, it's open ended. Help folks help you easier.
what am I doing wrong?
❤️ my apologies for taking it that way then
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ThirdPersonMovement : MonoBehaviour
{
public CharacterController controller;
public Transform cam;
public float speed = 6f;
public float turnSmoothTime = 0.1f;
float turnSmoothVelocity;
// Update is called once per frame
void Update()
{
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;
if(direction.magnitude >= 0.1f) {
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
transform.rotation = Quaternion.Euler(0f, targetAngle, 0f);
Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
controller.Move(moveDir.normalized * speed * Time.deltaTime);
}
}
}
What's the issue? Gravity?
your character wants to be at 0 Y axis
You have a CharacterController AND a Rigidbody on your character
They are fighting each other
i think so, but is look like he lagging
thats ur camera because of rigidbody probably
i remove rigidbody , but now my player is flying
Apply gravity through code.
ok
You haven't implemented gravity in your movement script
It's just doing what your code is telling it to do
How to fix license error
done!
can someone help me with this pls or is not clear enough???
https://discordapp.com/channels/489222168727519232/1152967965319381186
been stuck on it for like 3 days
You might want to check with the advanced section
thx I dunno what even qualifies as beginner, advanced and general lel
am i allowed to send a long error code here
Maybe just a screenshot first?
alright
i googled it apparently its just a bug
but i wanna make sure its nothing serious
yeah doesn't seem too bad. if it's not affecting your files then it should be fine
how to Deep copy this:
noteCreateTime = midiPlayer.GetComponent<MidiPlayer>().noteStartMS;
What is it?
List<double>
var copy = new List<double>(noteCreateTime);```
public class MoveSystem : MonoBehaviour
{
public event EventHandler OnTimer;
[SerializeField] private GameManager manager;
int nr1 = 0;
int nr2 = 0;
private void Awake()
{
OnTimer?.Invoke(nr1, EventArgs.Empty);
}
private void Update()
{
if(manager.state == GameManager.State.Playing)
{
nr2 = nr1;
nr1 = Singleton.Instance.time.ConvertTo<int>();
if(nr2 != nr1)
{
OnTimer?.Invoke(this, EventArgs.Empty);
}
}
}
}
How do I send a parameter with the event? I want to send nr1 with the OnTimer event to everyone subscribed but I don't know where to place it
isn't EventArgs.Empty a bit of a clue?
trust me I've tried and failed so many times I had to ask
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AnimationStateController : MonoBehaviour
{
Animator animator;
// Start is called before the first frame update
void Start()
{
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if(Input.GetKey("w")) {
animator.SetBool("isWalking", true);
}
if(!Input.GetKey("w")) {
animator.SetBool("isWalking", false);
}
}
}
what is wrong?
same GetKey
one is !
also you really nead to learn how to ask questions
Maybe tell us what is wrong or the unwanted behavior that's occurring.
you only have a transition from Idle to Walking but not back again
I connected the idle animation, taken from mixamo, connected in the animator, and also the walking animation but when I start the game, no animation appears. The character goes underground and appears to be sitting on a motorcycle
I've already tried both but it still doesn't work
the transitions have settings
yeah
i remove the has exit time, and i add the conditions isWalking = true
Yeah like what SteveSmith said, you're missing the way back
sounds like youve wired up the wrong animations
Try cs void Update() { if(Input.GetKeyDown("w")) { animator.SetBool("isWalking", true); } else if(Input.GetKeyUp("w")) { animator.SetBool("isWalking", false); } }
nothing change
same 😦
Your animation is likely setup wrong.
Ask the dudes in #🏃┃animation about your animation. Show them your setup and stuff.
I think that's a Synty model btw
Agree. I own it as well.
Or one of those other low poly ones etc
yeah then I don't think it's a rig problem, it might be due to his animation controller setup is the more likely cause
how do i follow a gameobject in scene view during play-mode?
Shift-F
or double tap F, one of those
thanks
Hey, I was watching a tutorial and the URP creation options are totally off from one another.
This is what the tutorial options show
My options
i made that my game is in 1920x1080 and still my game is wide (my monitor is 2560x1080)
Which one should I pick to stay consistent with the tutorial
how can i fix that
Probably the wrong channel #archived-urp
How did you set the settings for that? Specifically "Resolution and Presentation" options
in the unity editor on the right side of the display button
I am following a tutorial and i go to a point where i need to add a prefab as a rigidbody but it doesnt work
"doesnt work" that doesn't help
What do you mean "add a prefab AS a rigidbody"?
Let me refer you to the right place hold on I'll get the screenshot
under project settings
i found it, thanks 🙂
does anyone have a syntax on how I can pass an int in an event
because I still don't get it
You make your event take a delegate that has an int parameter. Then when you call it you'll just pass in an int and it'll pass that as a parameter to all registered listeners
wait I think I got it now
public event EventHandler<int> OnTimer;```
so I do this right?
now instead of the stupid EventArgs I do myInt
public event Action<int> MyEvent
cs MyEvent?.Invoke(69)
You could also use custom delegates
https://gamedevbeginner.com/events-and-delegates-in-unity/
thank you, I never knew what the <> are supposed to do in C#, I thought I need to pass it in EventArgs as some kind of dictionary cuz I was confused
hey i need some help, i have this object and i want it to rotate like a turret to a target, but i cant ge it to rotate around the right axis
how do I create a custom sprite and generate a custom physics shape with an outline tolerance of 1 instead of the default 0?
with code
Angle brackets declare a type for a generic class. So like when you make a list, they're programmed to be be a list of "generic" types, meaning the type itself is a variable. The brackets are what you're choosing that type to be. (E.g. List<int> myList;)
In the case of a delegate, the generic type is for the parameter
Oooof yeah there's a lotta stuff that can be easy to gloss over
i mean i dragit here
at script
at Rb 2d
I went two years in uni without knowing what a foreach loop was 😓
I remember when I created my own normalized vector without knowing unity has a normalize function
Damn RIP
Paddle is the one i want to put there
So uh can someone help me? I want to generate a custom physics shape using the Sprite Editor but with code for a sprite generated at runtime
with an outline tolerance of 1.
no idea how to do it though
The type in your script is a rigidbody, while you're trying to drag a rigidbody2D
fixed it thanks
Glad you got it resolved, but for future reference, you were wanting to "reference the rigidbody on a prefab"
Also, keep in mind that there are many of components and methods specific to 2D
If it won't let you drag it in, (or doesn't work in some other way) check for a 2D version.
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
i gave a gameobject the button component and still cant click it
is the gameobject hidden/obstructed by something else in the ui?
Make sure the game object is active. Make sure the button script is active. Make sure the object is under a Canvas. Make sure you have an Event System in the scene. Make sure no other UI objects are in front, that could prevent the click from reaching the button
yes by a text that says Play
so how do expect to click button
ok thanks for the help
i thought i wouldnt block the button
thanks for the help
always check the Rect Transform sizes /gizmos.
you can disable reciving raycasts for that text itself
btw thx for the saving tutorial on youre yt
np! 🙂 writing cloudsaving rn
yo if you make a cloudsave tutorial you're a godsent
🙂 working on it as we speaking using Unity Cloud, plus alternative solutions for those without Free Plan CC
yeah, I looked everywhere for cloudsave as I need it in the future, found tutorials on azure and other stuff but not on unity cloud
yeah cloud save on unity is fairly new!
what makes it more useful as of recently, is the ability to create new users with email/password instead of third party Authentications like Facebook etc.
cool, that's exactly what I need since I want to be able to save progress between devices
Hi, i've got a question about performance.
If i want to access to a public variable in a script which has no duplicates in the scene, is it better to have a reference to the object owning the variable, or making the variable public static so i dont need to reference the object?
Reference the script itself. I would avoid making it static
But without details, can't really say more. It MIGHT make sense to make it static, but it is often not a good idea for just ease of access
Well, since i have no problem in referencing the script through the inspector (both objects are always in the scene), and i was only using it to keep the inspector cleaner, i guess referencing the script is the way to go. Ty so much i can imagine making the vars public static has some other use that i'm not aware of and i was just being lazy
Static guarantees there will only be one instance
whats the best way to rotate an object on one axis without touching any of the other axis? orientation.rotation = Quaternion.AngleAxis(yRotation, orientation.up);This is what I have so far but it is not working.
use DOTween
This doesn't seem like what I'm looking for
why not?
you can even smooth this up without using any your own Lerp funfctions etc
Object Reference Issue
Im looking for a function that doesn't rotate every frame, I just want it to update when the mouse moves
That's why RotateAround isn't working for me
DOTween will work just fine
you didint answer my "Why not" question
im not talking about RotateAround
Frozen is never true but dont know why
how do I get intellisense for DOTween?
its an external asset
get it from asset store, watch tutorials on dotween
I figured it out
can someone take a look at my thread
I tried it and this isn't what I'm looking for
I need a tool that can rotate just one axis without ever touching the others
transform.Rotate will do that just fine, you can even tell it to rotate along the world-space axes instead of the local ones by default
the problem with that is it adds to the rotation, I want it to directly change the existing values
Then you can use Quaternion.Euler(x, y, z) and pass the angles in degrees
It gives back a Quaternion you can assign to any transform.rotation
but that involves setting all the axis values even though I only want to change the y
I wish there was a way to add quaternions like you can with vector3
Set them to their current values. That is basically the same as NOT setting them
Multiply them to accumulate quaternions
But that would be just equal to using transform.Rotate
What you can do is store individual x, y, z as floats in the script, change any of these variables and construct the quaternion on the fly
idk why but this just results in violent flailing
Hello everyone,
Im completely new to this and I hope this is the correct channel
void Update()
{
while (Input.GetKeyDown(KeyCode.Space))
{
rb.velocity = Vector2.up * upwardsForce;
}
}
I want my player to move upwards while the spacebar is pressed. However instead of working, my unity freezes the moment I test my game and press spacebar once. Where did my thinking went wrong? Any tips?
don't use a while loop. Update is called every frame so just use an if statement
It's because of the while loop. Unity does not render the next frame until all the scripts have finished running. And since Input.GetKeyDown can only change between two Update runs, then your condition is always true, your loop never ends, and unity freezes because it does not render the next frame
You will need to force stop Unity through task manager, unsaved progress will be lost
Oh, makes sense, thanks.
How would I implement my goal if not with a while loop? If I use an if statement I have to press my spacebar everytime I want my player to go up, however thats not wuite what im aim to achieve.
Just an if statement yes
If it's a "go up while you press the key down" thing, then use Input.GetKey() instead
Input.GetKey(KeyCode.Space)
i made a simple script for crouching but now when you crouch the only whey to stop is to sprint there is my code
GetKey is countinous
GetKeyDown is for single frame
Please share !code according to the instructions below
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Screenshots of code are not editable, copyable, and do not include line numbers
And please format the code before posting, so the indentation is correct
hi guys someone know some tutorial for make a teleport inside an house?
triggers + transform.position =
thxxx!
Im very new at unity (1 month old~) so don't go rough on me for my newbie question but i need some light in my head maybe someone can help.
I have a very basic scene setup where the cube spawn exactly a position where a empty gameobject called "Spawner" is located. This spawner is the child gameobject of the Parent.
Parent's XYZ position is: 0,1,2
the Spawner XYZ position is: 3,0,0
I also made a simple blue cube saved it as a prefab (its XYZ position is 0,0,0 but since i spawning it and set its coords it doesnt matter i guess).
Then i made the spawner.cs script and put it on the Parent gameobject. Pressed the pause button then the Start because the code is inside the start method. I also debugging 2 times which gives the box XYZ coords back to console.
First it says the XYZ is: 3,0,0 ( so it spawns exactly where the spawner is.)
Then it says the XYZ is: 3,1,2
In the code i update the cube position two times. Once with transform.localPosition and then with transform.position
What i don't understand when i update it second times shouldn't the position be 0,1,2?
As far as i know, transform.position is for the 'world position' and takes values from the gameobject where the script sits on. With this example it should be the Parent but it ignores the X axis and only updates on YZ.
public GameObject boxPrefab;
public GameObject spawn;
private void Start()
{
GameObject boxPrefabGameObject = Instantiate(boxPrefab);
boxPrefabGameObject.transform.localPosition = spawn.transform.localPosition;
Debug.Log("Box position is: " + boxPrefabGameObject.transform.localPosition);
boxPrefabGameObject.transform.position = spawn.transform.position;
Debug.Log("Box position is: " + boxPrefabGameObject.transform.position);
}
you're using it wrong 🙂
so the spawner's parent is at 0,1,2 in world space and the spawner is at 3,0,0 relative to its parent. that means the spawners world space position is 3,1,2
the position you see in the inspector is the local position
Before writing to this file, I want to clear it of all previous content
How do I do that?
I tried different things like opening the file with trucate mode and closing it but I did something wrong, cuz it didnt work at all
why are you using File.AppendText if you want to overwrite the content that is already there?
Not versed in all the different kinds of writing to files
you don't even need to use a StreamWriter for this. just use File.WriteAllText
First time, actually
I just used that cuz that's what came up when I searched how to write to a file
I'll try that thanks
So I know that if I have a script that updates a text file it doesn’t tend to update until I tab out then back into unity where it does the loading thing
How do I trigger that behavior from script so I don’t have to tab out and in to update stuff?
are you referring to it refreshing the content of the text file when viewing it in the editor? because you can just reimport the text asset with some editor code
https://docs.unity3d.com/ScriptReference/AssetDatabase.ImportAsset.html
Ah yeah I think so thanks!!
If I have 2 identical components in an object and I use the GetComponent<>() function to get one of them, how do I choose which one I want or switch between them
they are the same components but hold different data which I have to access from a 3rd function
you don't get to choose or switch. GetComponent will return the first component it finds of that type. you could instead use GetComponents and that would give you an array of all of the components of that type which you could do whatever you need to with. a better option would be to serialize references to those specific components and/or have them on separate child objects
didn't know GetComponents was a thing
the child thing won't work for my use case so I'll try the GetComponents instead
Hey pt1 🙂
#archived-resources message
thank you!
so the GetComponents got me to a different question, how do I go through them in a loop
A foreach should work
The components would need some identifier to distinguish them
like
for (int i=0; i<endvalue;i++) {
do stuff} ```
doesn't work because idk what's the endvalue
the length of the array
yeah idk how to find that out
array.length
ah thank you
Ok, thought so. Thanks
wish I would've done c# in school instead of c++
its pretty easy if you already learned C++
we only did fundamentals, from functions to algorithms and classes, structs and all those basic things
didn't get into any software specific application
thats all you need pretty much
schools rarely teach it, and really all you need to learn from schools is the concepts. swapping from c++ to c# shouldnt be that tough syntax wise
just cmd apps
if you learned like functional programming, then swapping to something else would be pretty hellish
or tried to swap into it
yeah I got the hang of it quickly
hello
best way to learn straight up coding/logic
still got a lot to learn tho
which is why I am here rn
this place is best for API specifics for unity programming
do you have visual studio ? create a nice Console apps
You can use unity too ofc and run it in 1 script to keep it simple enough
yeah I have visual studio
btw this is good to learn how unity works behind the scenes with your code (Monobehaviours) https://docs.unity3d.com/Manual/ExecutionOrder.html
ah I remember this, looked through it a lot whenever my game logic order got messed up and stuff happened in the wrong order
very useful
Hey guys, I was wondering, is there a way to Debug within only one C# script?
When I press "Attach to Unity" and try to debug my code, after it has gone through code in Update(), it jumps to cinemachine script and user input script, but I would like it to go on to FixedUpdate() within the same script instead. Is that possible?
are you putting breakpoints ?
I put one breakpoint, in a function that runs in Update(). Should I put more than one?
if you want multiple spots to hit sure. I think you want StepOver iirc so doesn't leave the script and just goes to next breakpoint
instead of step into
I could be remembering wrong though lol maybe someone will correct
Yeah I tried step over, and now use 2 breakpoints (one in Update() and one in FixedUpdate() ) but it still keeps going into the canvasScaler, externalTools, cinemachine etc etc after Update() instead of going into FixedUpdate().
hm 🤔 I am new to this debugging tool so I might be doin something wrong here