#💻┃code-beginner
1 messages · Page 409 of 1
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
okay
Im trying to make a marker for my minimap, I can move around the map with right click and left click is suppose to move the marker to cursor place, but the coordinates are wrong, how do I fix this?:
This checks if your mouse is over the map.
{
PointerEventData EventDataCurrentPosition = new PointerEventData (EventSystem.current);
EventDataCurrentPosition.position = new Vector2 (Input.mousePosition.x, Input.mousePosition.y);
List<RaycastResult> result = new List<RaycastResult> ();
EventSystem.current.RaycastAll (EventDataCurrentPosition, result);
return result.Count > 0;
}```
**This moves movePoint2 to where the mouse hit.**
```if (IspointerOverUiObject ()) {
if (Input.GetMouseButtonDown (0)) {
ray = cam.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, out hit, Mathf.Infinity, mask)) {
movePoint2 = new Vector3 (hit.point.x, hit.point.y, hit.point.z - offset);
}
}
}```
That returns an int. You can just use >
yh but my if statement looks like this if (hour > 21 && hour < 6), but if its lets say 22 hours it wont be less than 6
Well, yeah, because 22 is not less than 6. && doesn't make sense here, there's no way it can satisfy both conditions
but it has to be at night
Right
so like you know when its night time and its dark
Try speaking in complete sentences . . .
What am I doing wrong here? Everything works correct except checking if the tile is blacklisted and should return false.
public Tile[] BlacklistedTiles;
public bool CanSpawnOnTile(Vector3Int tilePos)
{
TileBase tile = GameMap.GetTile(tilePos);
if (tile == null)
{
return false;
}
if (BlacklistedTiles.Contains(tile))
{
return false;
}
if (!IsWithinSpawnDistance(tilePos))
{
return false;
}
return true;
}
public void GetSpawnPoints()
{
for (int x = GameMap.cellBounds.xMin; x < GameMap.cellBounds.xMax; x++)
{
for (int y = GameMap.cellBounds.yMin; y < GameMap.cellBounds.yMax; y++)
{
Vector3Int localPlace = new Vector3Int(x, y, 0);
if (CanSpawnOnTile(localPlace))
{
Vector3 place = GameMap.GetCellCenterWorld(localPlace);
spawnPoints.Add(new Vector2(place.x, place.y));
}
}
}
}
what debugging steps have you taken? if its not returning false, then the array doesnt contain the same instance of the tile
What's happening that shouldn't be happening?
It's adding spawn points ontop of blacklisted tiles, I added a Debug log in the
{
return false;
}```
And it never gets called. The tile is added to the array in the inspector.
I figured it out
I had two tile maps one named obsticles and another for the ground, the ground is the tilemaop attached to the script that was painted under the Blacklisted tile in the other tilemap. Erasing the painted ground tiles under the obsticles fixed it. cause then it returns null.
if (BlacklistedTiles.Contains(tile))
{
return false;
}
Pretty sure with the setup I have this code becomes unreachable.
still worth having for future tiles that might not want things to spawn on.
Hello everyone, im learning about 2d games. I want to do some practice. Can you guys suggest me any game idea for reinforce my basic knowledge? i made a quiz game and a basic platformer. I want to try something different.
What do you want to focus on?
actually i want to make my own platformer game but my idea is hard to make for me right now.
This is the code channel, so maybe ask folks in #💻┃unity-talk
okay sorry
Not any more than lists. Though it depends on how you're using them.
Hello
foreach (int i in Enumerable.Range(0, 2))
{
GameObject column = Instantiate<GameObject>(new GameObject("Column"),CardGrid.transform);
column.AddComponent<VerticalLayoutGroup>();
foreach (int j in Enumerable.Range(0, 2))
{
GameObject cardObject = Instantiate<GameObject>(CardPrefab, column.transform);
Card card = cardObject.GetComponentInChildren<Card>();
card.Initialize(chosen[i*3+j]);
}
}
Any specific reason this code would fail when i*3+j = 4?
I keep debugging but have no idea why
It's supposed to create columns of 3 cards but it only creates 2 columns of 2 cards before giving ArgumentNullException...
Curiously, it creates 2 columns outside of CardGrid, which is insane
Hey! Anyone have an idea for the simplest way to know which direction is the shortest distance between two points on the circumference of a circle? Once my enemy comes into a radius around the player it rotates around the player until it reaches a collider (player's gun) . I want to make sure it always rotates in the direction that is the shortest distance.
It's a little over my head so if you know where to start lmk!!
Thanks :)
Working in Unity w/ C#
Nah, it just depends how you're using it. A Queue<T> is for constantly adding and removing elements as those operations are fast, but you cannot index specific elements. If you need to access specific elements (indexing), then List <T> is preferred as removing and adding are expensive . . .
Hey guys. Im working on a quiz game and currently trying to implement the ability to select from a list of quizzes - for example, a quiz about computers, a quiz about video games, etc. - I have one list for each quiz that has a certain number of scriptable objects with the question and answers. I want a way to add these lists of scriptable objects to another list called quizzes so that I can access them by an index number and populate the questions and answers in the quiz. How would I go about doing that? Is there a better way to do this rather than a list of lists?
Create an SO that holds a list of quiz SOs, then drag your quiz SOs to the list . . .
You can do it manually or write code to add all quiz SOs to the list automatically . . .
im using it as a rolling frame/sec counter.. ```cs
//current frame rate
frameCounts.Enqueue(fps);
//older than averageDuration
while (frameCounts.Count > 0 && totalTime - frameCounts.Peek() >= averageDuration)
{
frameCounts.Dequeue();
}```
it runs every frame so i was curious
ya, i might use a fixed array
float[] frameRates = new float[BufferSize];
No reaction gifs . . .
That looks fine. Adding and removing are O(1) because there's no shifting involved . . .
ok thanks 👍 i wanted someone more experienced to give it a look
I don't understand your question.
Distances don't have a direction
You could think of the direction from A to B or from B to A
I think I need to calculate which angle is smaller ("left" or "right" of the enemy towards the gun) and then choose whichever direction is along the smaller angle
i think he means like if the guy is almost turned 45* away from the direction it should look.. instead of rotating around the opposite direction 315* it rotates back the 45* rotation
yeah exactly
You could use dot product between OA and OB
Where O is the center of the circunference
If it's negative, then A is "up" B, therefore rotate - (360 - angleAB)
If it's positive, then B is "up" A, therefore rotate angleAB
I just took this off my head so it might not work as I have no way to pen test this xD
@orchid hatch
so I would do Vector3.Dot(OA,OB) ?
scratch that
what you should use is the dot product between OA and Rot90(OB)
Because that way, if the sign changes it means crossed OA
in other words:
var dot = OA.x*-OB.y + OA.y*OB.x;
if(dot > 0)
console.log("OB on the right of OA")
else if(dot < 0)
console.log("OB on the left of OA")
else
console.log("OB parallel/antiparallel to OA")
antiparallel eh?
I guess both are parallel lol
😄 lol
var dot = OA.x*-OB.y + OA.y*OB.x; lookin scary
i always have to look back on dot, cross, and atan
just rotate OB then take its dot with OA :p
me too and it's always interesting/fun
bout to make a gun turret, i'll be doing this myself soon
@orchid hatch
Cool!
Wanna see the result :p
It seems to give inconsistent results depending on where it approaches from
oh i just saw the scratch that
nvm
that's because it's the wrong answer :p
haha
ok i'll try this!
i think it works!
though it gave the seemingly wrong direction a couple times but every other time it's right
it seems like there's one specific approach that confuses it
i'll take a video
hmm okay once i started recording it's actually wrong a lot of the time
rats
here's my code ignore the direction bool lol
Oh ok, so the player is that little dog, right?
And the pistol(collider) is the cursor?
Oh, my mistake
try dogToBat.x * (-dogToTarget.y) and see if it resolves
the player is the dog and the bat's target is where the bone/gun is
it should be a minus sign
try this as "dot"?
is tostring still works on class that is null
nah, try this:
float dot = dogToBat.x * (-dogToTarget.y) + dogToBat.y * dogToTarget.x
I used the wrong sign and misled you, sorry :p
oh my bad i missed the minus sign that was there in your original response
You didn't miss it, I edited it later xD
@remote osprey in practice c:
Would like to see that. I did a test on a design pattern using a turret a while back. It was mainly a separation of concerns using an individual script for each action the turret can do, but I used SOs as pluggable behavior for each script . . .
What a cool little game! UwU
I your pixel art, it has such a light feel to it :p
I hope you do!
I really feel like playing this, feel free to tag me when you release it :p
cool will do!!
Hey, I’m looking to start programming what do you guys recommend that I learn first
C#
I'd you can start with anything you like!
If you want to get into gaming, you could try using something simpler like GameMaker
But if you just want raw programming, you could pick any of the major languages, really
Like Java, C#, Python, whatever is more directed to what you want
since you're here, C#. you can check out the pinned messages in here to get started . . .
C# is more directed to Unity, since that's what you seem to be more intested in
Mentions major languages. Forgets C/C++ 
Yeah
for what it's worth I found the way gamemaker simplifies things and uses visual scripting to be kind of confusing as a beginner & it was more useful to just start learning c# by messing around in Unity and looking up things that I didn't understand
i was going to say smth, but nah . . .
Memory allocation 
I both like and despise C
It gives me so much control but but
(Segmentation Fault)
Any opinions on when to run the initialization for my state machine? Trying to decide between Start() and Awake. The former seems the most stable but I'm not sure if that's a good take.
use Awake to initialize its own variables, then Start to access other objects
Gotcha. Thank you! I was reading the page but the dots weren't connecting in my brain.
And the order in which they execute is the opposite when initializing during gameplay?
no, GameObjects already existing in the scene will call their Start method called before an instantiated GameObject will call its Awake method . . .
Got it. So it's *not *a reversal and more so the order in which they execute? GameObject already existing will do Awake() into Start(), and then another Awake() runs after that for the instantiated ones?
Awake and start are called in the same frame. So objects that exist when runtime starts will have both called the first frame of runtime (with the first start being called AFTER every awake). An instantiated object may be called IN that first frame, but I believe the object isn't actually created until the very start of the next frame? It will at least be later no matter how soon Instantiate is called
ahh
This is helpful to look at too.
https://docs.unity3d.com/Manual/ExecutionOrder.html
start by learning to code. there are beginner c# courses pinned in this channel
then why are you here
coding is kinda necessary to make anything with logic
it doesn't have to be writing code, unity has a visual scripting system
but you will still have to create logic
my guy, how are you going to go into a code channel, ask how to get started with unity, then say you don't want to learn to code
drag thingys
if by that you mean blocks, yes, unity has visual scripting.
watch yt
you could do that to learn, but you can't just copy everything forever
you actually have to learn
why would being 2d have an influence on being multiplayer
you absolutely need to learn to code if you want to do anything remotely related to multiplayer
if you want it to have multiplayer, you have to make your game support multiplayer
learn
there's resources in the pinned message
you've been told that already
you don't, not yet.
learn to actually make it first
then add multiplayer
don't get ahead of yourself, you'll just create a nightmare for your future self
guys, ive been learning the creative core thing but yeh i mean it gets you through how to a 3d environnement which is fine but i thought i need much that 3d knoweldge for a mobile game
like i would more interested in like the architecture of a mobile game for exemple, idk how to explain it yeh yeh designing a 3D environement isnt it cuz 3d environnement will be like 1/5 of my game
....ok, what's your question?
hmm my question like where could i learn that i guess
learn... what?
aside from user interfacing, a mobile game isn't much different from any other environment
you can google for tutorials on how to make multiplayer games. no one here is gonna spoonfeed u all that you are looking for, especially since you said you dont wanna code
probably not an import, the environments are fundamentally different
repeating the question is just spamming, this isnt even a code question.
if you can make a fully functioning game in scratch then you already know how to write logic
just rewrite that logic using stuff unity understands
there's no shortcut for this
ok, go learn then
plenty of resources exist
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
It would take weeks of one on one help to "just tell you".
You need to put in the work yourself. If you have SPECIFIC questions, we can help. But you're questions are simply not how any of this works.
People pay a lot of money for what you are demanding for free
yes
this guy must be a troll
Learning c++ and spending the time learning
Ask in an unreal server
But first put a tiny bit of effort in by yourself.
<@&502884371011731486>
They can see deleted comments. Clearly not a misclick
You are the type of person that is going to struggle really hard
!ban 1145876377992712242 offensive crap
chatisbest101 was banned.
is there some guide out here to learn the basics principles of an idle (plays itself) mobile game rpg style? i know i could do it how i think it should be done but im sure il shoot myself in the foot and waste big amounts of time to implement stuff that is already establish
where would i store variables such as volume and player health? in a GameManager script attatched to an obj, scriptable object, static float... im really confused
the main point is i need them to be adjustable / updated across scenes
store them in an object that makes sense to have them. for example why would the GameManager need either of those variables? the player's health should be stored on whatever component manages its health, and the audio volume should be stored on whatever deals with changing the volume
maybe im overthinking it but for example, i currently store my volume float on a SoundManager in scene 1 with donotdestroyonload() setup, and when i want to edit it in scene 2 it doesnt work when i call SoundManager.instance.volume since i didnt load scene 1 yet
im not sure how to overcome this problem
This isn't necessarily what you need to do, but what I personally do is put my settings into a static class, when the game is launched I load the settings from disk and apply them to that static class. Then when something has changed them I save the settings to disk again.
so should i have the same SoundManager on both scenes?
if you are using a singleton instance to manage that though, you'll need some way to ensure that an instance of that singleton exists. either by putting extra copies into your scenes, or by instantiating it when it doesn't exist
ahhh ok
public void EjectObject(Item item)
{
if (item == null || item.quantity <= 0 || item.ground_prefab == null)
{
return;
}
GameObject g = Instantiate(item.ground_prefab, drop_Target.position, drop_Target.localRotation);
if (g.GetComponent<Rigidbody>())
{
Rigidbody r = g.GetComponent<Rigidbody>();
r.AddForce(playerCam.transform.forward * EjectForce / r.mass);
}
}****
can anyone help me why my object is spawning like 5 meters away from me and in wrong rotation
its just not spawning at target_drop
We can't help you because this tiny snippet of code has nothing to do with the location of your object. Please properly share all the !code related, preferably the whole class to avoid confusion with relevant context
📃 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.
Hello guys! This code sets a ScriptableObject parameter in ScriptableObjects at runtime, but when I stop running it, it's not saved anymore in the ScriptableObject. Why?
private void ApplyDinosaurDataToItems()
{
DinosaurItem[] dinosaurItems = Resources.LoadAll<DinosaurItem>(dinosaurItemsPath);
foreach (DinosaurItem dinosaurItem in dinosaurItems)
{
dinosaurItem.dinosaurData = Resources.Load<DinosaurData>(dinosaurDatasPath + $"/{dinosaurItem.name}");
}
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
you need mark the SO as Dirty. Look at SetDirty
omg, it works now, thanks ❤️
you do realize that this will not work in a build
No? I think it would
Oh sorry, I didn't mean it like that. I won't use this in build.
I thought you mean the ScriptableObjects won't work. Sorry!
I have a problem with Collision2D.
I have multiple gameobjects (counters) close to each other. I need my "player" gameobject to collide with one. But "player" tends to collide with 2 counters at same time.
My solution - Can be ignored - spent 3 days.
I solved that by changing layer of "counter" dynamically to "collidable", based on my what "player" must collide next. And setting up my layers such that the other counters dont initiate "CollisionEnter2d". And on CollisionExit , I change back the layer to "non-collidable".
Now, I have N no. of player gameobjects, that can collide as their algorithm dictates. There is no user input.
My use case is , any player can collide with any counter.
So, if I have changed counter layer to "collidable" for 1 player, other players may collide it by mistake.
And I can not control when to disable "Collidable" state, as other player may have same target.
What other way I can solve this ?
probably this is what you need to implement
https://docs.unity3d.com/ScriptReference/Physics2D.IgnoreCollision.html
Thanks @languid spire I need the opposite of it. There are N no, of counters and M no. of players. Might be too costly to set Ignores for NxM ?
what I would do is to set the collision matrix of the players and the counters to ignore eachother by default then you can use IgnoreColllision with false to activate specific Player Counter collisions
Ohk ! That sounds promising. Thanks a lot @languid spire
i dont understand what is singleton coding pattern?
Singleton means the instance is guaranteed to only have a single instance. Singleton instances also usually have a direct reference to it through a static property on the class.
It is useful for things like managers that usually only have one instance in the game. You can easily access it and its data this way.
Unity had a great live session explaining/highlighting how to use singleton patterns, but I can't seem to find it anymore. That's where I'd usually direct people
thanks
I would just read this https://unity.huh.how/references/singletons
How can I assign Gameobjects in different scenes to scripts?
generally you would use DDOL objects and a Singleton game manager
because it can only be done at runtime
Can you share a written source or a tutorial? I never knew of anything like this before.
Google is a great source to find it
make sure you read this before learning about singletons
- https://gameprogrammingpatterns.com/singleton.html
- https://gameprogrammingpatterns.com/service-locator.html
and don't skip the discussion of pro/con
I can give you Pseudo Code
LoadScene(0)
Instantiate GameManager as a Singleton DDOL
LoadScene(1)
Set GameObjects to save as DDOL and inject them into GameManager
LoadScene(2)
Access gameobject from Scene1 via the GameManager
A C++ explanation about singletons when we're using C#? 🤔
Two out of three cons also apply here. Only the coupling one, which I'd argue doesn't really matter for a beginner
Ok
Thank you Steve and everyone else.
The language doesn't matter, its a software design pattern.
it does when you are trying to explain concepts to a complete beginner
Physics2D.IgnoreCollision(player.GetComponent<Collider2D>(), counter.GetComponent<Collider2D>(), false);
When I make IgnoreCollision false, the collisionEnter2d is not called,
Is that expected behaviour , for IgnoreCollision
that should work. Are you sure you are doing it at the right time?
charactersPerSecond.ToString();
charactersPerSecond = tagValue;
tagvalue is a string and CPS is a float. i get a red squiggly line on tagValue that says cannot convert string to float. any ideas??
Yeah I am sure. Now, I am testing by to setting ignore as true manually for all. BRB
is charactersPerSecond the varname?
yes
You're reaching it wrong. You're basicly doing:
- Turning charactersPerSecond into a string, but do nothing with it.
- Trying to attach a string to charactersPerSecond (which is still a float)
i tried putting the to string and = tagvalue on the same line but i get the same error
thats why i tried seperating them
that's really wrong
how am i supposed to do it tho?
You can't do that. C# doesn't work like that
Turn tagValue into a float or create a new variable which is a string
C# isn't dynamically typed like Python
charactersPerSecond = charactersPerSecond.ToString();
charactersPerSecond = tagValue;
like this?
oh okay ill try that
this wont work as charactersPerSecond's type wont change accordingly
String newCharactersPerSecond = charactersPerSecond.ToString();
newCharactersPerSecond = tagValue;
create a new variable
wait
no
ohh that makes sense. thank you!
that doesn't work either
Why do you want to assign a string value to something that seems to be numeric? Don't you want to assign a numeric value instead?
is the issue that the value you try to assign is a string?
This sounds like an XY problem so please explain
wait are you setting tagValue to newCharacterPerSecond or the other way round
you're overriding the variable right after you assign it's value
CPS to tagvalue
oh yeah
im using ink and in ink there are these tags and i want to set it so that when i type "cps:9" characters per second is going to be 9
how though?
So:
tagValue = charactersPerSecond.ToString();
its suppoed to be CPS = tagvalue
I think you need that
characterPerSecond is a number, tagvalue is a string.
you want to convert tagValue to a number, done like int.parse(tagValue).
afterwards you can set characterPerSecond to tagValue
So you have a numeric value and you need to set it to 9 when you type this?
wouldnt that set the tag value
yeah
Yeah nobody is helping you with an actual answer here
Your use case seems unnecesarrily complex
im not sure if you can do (int)tagValue but using int.parse is the best bet here
I'm also really confused what the goal is
setting characterpersecond to tagValue
Again, this doesn't help because the issue is completely different
Is the point of this code to set a variable based on its prefix?
I mean, I can answer it, but there's a lot of parsing involved
Isn't it what I've done above?
ill try that
whats the value of tagValue actually, are you sure its only a number?
Don't bother, it won't parse something like cps:9
I don't think half the people here read the actual question
i have a switch statement that checks if a tag starts with "cps" and then splits it with a semicolon and after the semicolon will get the number that i typed and SET it to the scripts character per second variable
tagValue is a string
If you really, really want to have something like this, determine the location of :, and get the string part before it and after it
tagValue is the second half of a string called tag which I just split with a variable
Then, int.TryParse the part after the semicolon and you can assign the result to the variable related to the part before
i already did that, its tagName and tagValue respectively
Okay, then just do the int.TryParse part. Don't use int.Parse unless it is guaranteed that the value is always numeric
thats what the switch statement i have does. tagValue is the part after the semicolon.
so to clarify,
tag would look like cps:9
tagName is cps
tagValue is 9
?
yes
ok yea then you can definitely int parse tagvalue
charactersPerSecond = float.Parse(tagValue);
this?
yuh
okay ill test it out real quick
if it works you should know about dictionaries too
rather than using this tag system
Manually setting is working fine. It seems to me, IgnoreCollision does not work when against Collision Matrix settings.
im do know about dictionaries but im following a tutorial so i prefer to just keep everything as is
What exactly is the point of this, though?
some day I will write some test code to confirm. too tired today.
Like I said, this is complex and I don't see what this achieves
dialogue system using ink
i want to change the speed at which the character talks to add drama and stuff
i heard of it i should prob give it a go soon
yeah it saves you so much time and its insanely worth it
should cost money but its free for some reason
in all honesty the format isnt that hard
but i think its a good start
a lot of people write their own node based dialogue manager when ink exists
thank you @languid spire my use case is solve with Ignore Collision.
i attempted to make my own node based one and it was insanely difficult
editor tools 
didnt work..
charactersPerSecond = float.Parse(tagValue);
text.maxVisibleCharacters++;
yield return new WaitForSeconds(1f / charactersPerSecond);
this is the thing im using for characters per second by the way
float
no
try printing out tagValue and charactersPerSecond to see
okay
..... weird, this is what it printed out. even tho in the ink file i set the cps to be 20 but it says 0.05
and tagvalue 20
okay nevermind it works
i accidentally commented out something
thanks for your help
🎊
guys please help me i set up my first person movement in unity and idk why it always moves me into one direction. I also tried to comment out some of the areas which have effect on the position one at a time to find the section with the error but i couldnt find anything
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[Header("Movement")]
public float moveSpeed;
public Transform orientation;
float horizontalInput;
float verticalInput;
Vector3 moveDirection;
Rigidbody rb;
private void Start()
{
rb = GetComponent<Rigidbody>();
rb.freezeRotation = true;
}
private void Update()
{
InputHandler();
}
private void FixedUpdate()
{
MovePlayer();
}
private void InputHandler()
{
horizontalInput = Input.GetAxisRaw("Horizontal");
verticalInput = Input.GetAxisRaw("Vertical");
}
private void MovePlayer()
{
//Calculate movement direction
moveDirection = orientation.forward * verticalInput + orientation.right * horizontalInput;
rb.AddForce(moveDirection.normalized * moveSpeed, ForceMode.Force);
}
}```
thats the main code of my project everything else is just a script to move the camera to an empty object attached to my player and the script to rotate the camera
what's orientation set to?
orientation is a empty child for my player gameobject
Debug your values so you KNOW what you are dealing with
are you sure orientation is rotating
wait
{
public float sensX;
public float sensY;
public Transform orientation;
float xRotation;
float yRotation;
private void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
private void Update()
{
//get Mouse Input
float mouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * sensX;
float mouseY = Input.GetAxisRaw("Mouse Y") * Time.deltaTime * sensY;
yRotation += mouseX;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
//Rotate cam and orientation
transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);
orientation.rotation = Quaternion.Euler(0, yRotation, 0);
}
}```
thats the script i use to rotate the camera
ok so is orientation set to the camera?
i dont know where orientation is in your scene
if it's even rotating
play the scene and check if orientation is rotating
and look more into debugging your code
it is
how
try pressing this big green button
ok wait
I get so many questions everyday on my videos of people asking why their code isn't working. Sometimes its a simple typo you can infer from an error message, other times its a deeper issue.
Many beginner tutorials first tell you to start putting Debug.Log statements everywhere, which can work and if done well can be a good practice - but its mu...
this is a fun watch
ty
i didnt know about the big green button until 1.5 years into unity 😄
even though i learned c++ beforehand I didnt know you can debug unity
tbh 'Attach to Unity' is a bit of a hint
i never looked at it tbf
rofl
since unity is the one running the game
wait you can debug with that?
of course, that's what it is for
it 'Attaches' your VS 'to' your 'Unity' project so you can debug in VS
are there any drawbacks to enabling debugging for all projects
i had that on for a while now
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class fridgeScript : MonoBehaviour
{
public GameObject inticon, fridge, fridgeOpened, fridgeClosed;
void OnTriggerStay(Collider other){
if(other.CompareTag("MainCamera")){
inticon.SetActive(true);
if(Input.GetKey(KeyCode.E)){
fridgeClosed.SetActive(false);
fridgeOpened.SetActive(true);
fridge.SetActive(true);
inticon.SetActive(false);
}
}
}
void OnTriggerExit(Collider other){
if(other.CompareTag("MainCamera")){
inticon.SetActive(false);
}
}
}``` is there a simple way to make the door close if i were to press e again?
only speed
Probably some overall overhead. Especially during recompilation and domain reload.
just set fridgeopen to inactive fridgeclosed to active
idk
me actually learning unity for about 1.5 years now xd
the 1.5 year mark where everyone learns about the big green button
like this? ```cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class fridgeScript : MonoBehaviour
{
public GameObject inticon, fridge, fridgeOpened, fridgeClosed;
void OnTriggerStay(Collider other){
if(other.CompareTag("MainCamera")){
inticon.SetActive(true);
if(Input.GetKey(KeyCode.E)){
fridgeClosed.SetActive(true);
fridgeOpened.SetActive(false);
fridge.SetActive(true);
inticon.SetActive(false);
}
}
}
void OnTriggerExit(Collider other){
if(other.CompareTag("MainCamera")){
inticon.SetActive(false);
}
}
}```
I got a big question if anybody can help me. I setted the Canvas Scaler to 1920x1080 ; The canvas render mode to the main camer. I putted some UI, anchored and when I change the resolution from 1920x1080 to device resolution 1560x720, the UI moves a bit and its uncentered as he needs to be. Anybody can help? To anchor the UI even more, so it doenst matter the resolution, UI stays the same?
Well you just create a Boolean, get the state of the door (if open or closed) and then add ! In SetActive
oh ok
Not sure about that tho
haha i think ive heard about it before but didnt really realize the power
thats normal, look into how unity UI works.
https://www.youtube.com/watch?v=QnT-2KxVvyk
This tutorial/guide will show you how to resize your Unity UI canvas, GameObjects, text, button and images. You will learn:
- How to fix Unity UI for every resolution
- How to adapt UI for mobile devices
- How to change Unity UI canvas scaling
💜 Join our Discord: https://discord.gg/hNnZRnqf4s
Timestamps:
0:00 - Intro
0:20 - Fixing main UI
3:23...
Thank you
tldr use this tab
then that is even more reason to have expected Debug.Log statements in your code
its a standard across a lot of UI editors. Figma has a near identical system. Godot lets you use either position or the standard anchors
do i add the ! before the "SetActive"
do you know what ! does
SetActive(!YourBool)
ok
bool yourBool = true;
Debug.Log(yourBool); // returns true
Debug.Log(!yourBool); // returns false```
we'll talk about ? another day 😴
@eager spindle I got 12 UI Images that are around the screen. Can I put all of them to the left side and then arrange them even tho some are the center or some are to the right?
idk what that looks like
I think you should ask here: #📲┃ui-ux
do i paste that into my code and change "yourBool"?
The idea is that I spawn some gameobjects around the screen. I arrange them with anchor and position through code but its work only one one resolution. With anchor and pivot
no
do not copypaste my code it is ass
and its not related to what youre doing
No, you should apply this logic into your code
oh ok
if youre not sure on what it does you should learn c# basics before going to unity
some people do wing it through unity but waste a lot of time because they dont understand basic coding concepts
So, you should take the state of your door in start(), save it into a bool, then when you check for your input, you set the setactive to !yourbool (you need to save the changes also to your bool, so the best is to set first when you get the input your bool to = !YourBool and then in the setactive(YourBool))
is this correct
Well no
First, Boolean is not a bool
Second, with that your door will only open and then won’t do anything else
i fixed it
In Start you need to get if your door is closed or open, you can get that by checking if fridge open or fridge closed is active or not
in the inspector?
i just did i realized i didnt have it there before
Incorrect, a Boolean is a bool. bool is a keyword referring to Boolean
is this right
Works fine, just adviced to use bool
So it works fine? Ok
It's an alias
Well no, again
Because if you press e you will get what you want only once
@eager spindle i have completly no idea why it does this im not pressing anything and i really dont know how i should debug this pls help me
I strongly advise you to learn unity before making a game
What are you trying to do? Open a door?
You don't need two booleans
open and close a door
Do you know what a boolean is?
a bool right?
well what does a bool do
Yes, but what is the point of a boolean?
how does it help you here
I think you are lacking some very basic c# fundamentals and I strongly advice you learn those first instead of making a game
yes or no
int xMax = Mathf.Max(initialGridPosition.x, currentGridPosition.x);
int zMin = Mathf.Min(initialGridPosition.y, currentGridPosition.y);
int zMax = Mathf.Max(initialGridPosition.y, currentGridPosition.y);
for (int x = xMin; x <= xMax; x++)
{
for (int z = zMin; z <= zMax; z++)
{
selectedGridPositions.Add(new Vector2Int(x, z));``` how could i trim the edges here to end up with a round pattern?
Not only is c# way different in Unity, you are effectively trying to learn two frameworks
Well, it’s a: true or false
thats nice
so do you know what SetActive does?
yeah
you said yes or no tho
for example "cube.SetActive(false); makes the cube unactive right
i did mean true or false
Ok
wtf i just disabled all of the scripts i use and it still moves exactly the same i created a monster its living rahh
Nice font you have there. Looks like the one from Minecraft or smt
yep its monocraft
minecraft font all over my system
its inconsistent though
Check your prefab position
haha nice. I screwed my last pc over. I used comic sans as default font. Forgot how to turn it back
in this image the new win10 font is used
Cool
this is beautiful.
using UnityEngine;
public class fridgeScript : MonoBehaviour
{
public GameObject inticon, fridge, fridgeOpened, fridgeClosed;
bool open = true;
void Start(){
fridgeOpened.SetActive(false);
fridgeClosed.SetActive(true);
}
void OnTriggerStay(Collider other){
if(other.CompareTag("MainCamera")){
inticon.SetActive(true);
if(Input.GetKey(KeyCode.E)){
fridgeClosed.SetActive(true);
fridgeOpened.SetActive(false);
inticon.SetActive(false);
}
}
}
void OnTriggerExit(Collider other){
if(other.CompareTag("MainCamera")){
inticon.SetActive(false);
}
}
}``` right now if i press e it stays closed
wdym? its all set to 0, 0, 0 and i dont have a prefab
Yeah because your bool is hardcoded
Why do you have two gameobjects for the door
Also
Why not just move the door
Why set something as active/inactive
one game object is the door closed anyother is it open
thats correct, you havent set it to check if the fridge is open or close.
In the section where you set fridgeClosed, add another section to check if the fridge is closed. if so, open the fridge. if not, close the fridge
we are not giving you code here and can only tell you so much
learn about the big green button today
it will help you understand what youre typing
You need one bool indicating the state, bool isOpen;
Then when you press the fridge and trigger a method, you set isOpen to !isOpen. This means true becomes false, and false becomes true.
Finally, depending on the final state you move the door to the correct coordinates.
You currently complicate this way too much
When it spawns, in what position does it go?
where it is just falling bc of gravity but it doesnt stay
this?
You still have two gameobjects you don't need
and I don't see the boolean being changed. You are merely using it in a method
So basically you don’t want gravity in your GameObject? Or it should spawn somewhere else
do you mean in the start?
Refactor your code so there is a single door. Put the door in a closed state, and then on opening the method will call isOpen = !isOpen;
Then, make an if statement that sets the door transform to the correct location
it should fall to the ground like a human would to but it doest it flies this weird curve and falls through the ground. even though i disabled all scripts which have acces to my player
Also, what is intIcon?
Try to block some rotation, go to your rigidbody and check one of your rotation
interaction icon for short
Ah okay
press play on unity BEFORE starting to record.. so that the first 50% of your video isn't you pressing play and waiting 😄
its litteraly frozen an all axis
is this right
would be a good idea if the main event isnt exaclty when it starts playing
Why do you call setActive twice? You call it once
oh yeah hold on
Also, I would assume intIcon should be shown if it's closed so this should depend on open
Unless the point is showing it until you interact with the fridge
thats correct
All you need to do now is remove the second SetActive and move the door depending on the state
And maybe rename the gameobject but this is more code style
so do i have 2 gameobjects? one being open one closed?
Idk then, maybe its colliding with the tree and that’s why you have that weird behaviour when you spawn
Only one
No, you have a single one that you change the location and rotation of
what behavior
The point is that having two is messy and this will not work properly
I mean that strange rotation at the start of the game
Like, what if you want it to open smoothly? Two gameobjects that appear and disappear do not work
Not to mention collission means you will be stuck inside the door if it opens, probably
oh yeah thats because the camera has a weird startposition wait
it cant be the tree i tried it on a flat plain before
#💻┃code-beginner message bumping this
I'm trying to make a movement system by myself and I got an error that I don't really understand saying that the expression '==' is invalid
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
public class movement : MonoBehaviour
{
//measured in unit per second
private float jumpHeight = 7f;
private float walkspeed = 5f;
private float runspeed = 10f;
void Update()
{
float verticalInput = Input.GetAxis("vertical");
float horizontalInput = Input.GetAxis("horizontal");
if (Input.GetKeyDown(KeyCode.Space)) == true;
transform.position = transform.position + new Vector3(verticalInput * jumpHeight * Time.deltaTime, 0, 0);
Debug.Log(transform.position);
}
}```
this
if (Input.GetKeyDown(KeyCode.Space)) == true;
is invalid C#
And besides that, == true is redundant either way
dumb method would be to check if the distance from the current tile to the center tile is less than the half width of the square
if (Input.GetKeyDown(KeyCode.Space)) is already enough
any of you guys know where i can find unity version 2017.4.9f1
Probably in the archive
thanks
its not there, there isnt anything in 2017
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class fridgeScript : MonoBehaviour
{
public GameObject inticon, fridge, door;
bool open = true;
void Start(){
door.SetActive(false);
}
void OnTriggerStay(Collider other){
if(other.CompareTag("MainCamera")){
inticon.SetActive(true);
if(Input.GetKey(KeyCode.E)){
fridge.SetActive(true);
door.SetActive(!open);
open = !open;
door.transform.Rotate(new Vector3(-90, 0, -90));
inticon.SetActive(false);
}
}
}
void OnTriggerExit(Collider other){
if(other.CompareTag("MainCamera")){
inticon.SetActive(false);
}
}
}``` is this right
Yeah, just checked myself, not sure then
its okay
Very close, you just need to rotate it depending on open
Right now you always rotate it the same way
Also, try it and see. Half the debugging is about seeing what it does
this kinda happened
do i add another if statement?
Yes, how else do you close it?
It just opens, then it opens again, and again
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class fridgeScript : MonoBehaviour
{
public GameObject inticon, fridge, door;
bool open = true;
void Start(){
door.SetActive(false);
}
void OnTriggerStay(Collider other){
if(other.CompareTag("MainCamera")){
inticon.SetActive(true);
if(Input.GetKey(KeyCode.E)){
fridge.SetActive(true);
door.SetActive(!open);
open = !open;
door.transform.Rotate(new Vector3(-90, 0, -90));
inticon.SetActive(false);
if(open == true){
door.transform.Rotate(new Vector3(-90, 0, 0));
}
}
}
}
void OnTriggerExit(Collider other){
if(other.CompareTag("MainCamera")){
inticon.SetActive(false);
}
}
}``` this is the code idk if its right but the door keeps disappearing
oh wait
@burnt vapor i fixed that but when i press e the door is gone
I want to be like this, and instead of that Its looking like this @eager spindle
make the dog a child image of the carpet
or the other way round
what you mean the other way round?
carpet a child image of the dog
but lets say i didnt have that solution. Why do I anchor it, put some positions throughtout the script and its still moving through ui
this is my main question
@eager spindle this was the code to setparent a gameobject?
myGameObject.transform.parent = carpet1.transform;
Why do you still have a rotation that is called regardless of the state?
it's either the open rotation or the closed rotation
Now it's either the closed rotation or the closed+open rotation
how do i do that
Instead of an if statement make an if-else statement
hello, i am making fps shooter and my camera is jittery
the player is a parent to the camera and when i move the camera (like rotation) it is fine but only when i start moving and rotating the camera the camera movement is very jittery
the rigidbody is interpolate, movement is in fixedUpdate as it is rigidbody movement, and cameramovement is in lateupdate
please help (tell me if you need to see any code)
got this by making a radius for x and z and checking the distance from the center tile, its pretty good but has a single pixel on the edge sometimes
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class fridgeScript : MonoBehaviour
{
public GameObject inticon, fridge, door;
bool open = true;
void Start(){
door.SetActive(true);
}
void OnTriggerStay(Collider other){
if(other.CompareTag("MainCamera")){
inticon.SetActive(true);
if(Input.GetKey(KeyCode.E)){
fridge.SetActive(true);
door.SetActive(!open);
door.SetActive(true);
open = !open;
door.transform.Rotate(new Vector3(-90, 0, 0));
if (open == true) {
door.transform.Rotate(new Vector3(-90, 0, 0));
}
else{
door.transform.Rotate(new Vector3(-90, 0, -90));
}
inticon.SetActive(false);
}
}
}
void OnTriggerExit(Collider other){
if(other.CompareTag("MainCamera")){
inticon.SetActive(false);
}
}
}``` is this right
You are STILL rotating regardless of state
How often do I need to mention this
Also
door.SetActive(!open);
door.SetActive(true);
I understand you lack basic knowledge of C# but surely you notice these mistakes?
Especially after I mentioned them three times
what do i do to fix it
screenPosition = Input.mousePosition;
worldPosition = cam2.ScreenToWorldPoint(screenPosition);
worldPosition.y = 1000f;```
>
```cs
if (Input.GetMouseButtonDown (0))
{
box.transform.position = worldPosition;
}```
Why is this not precisely on where the mouse is? its off by this much [Check ss below]
hello, i am making fps shooter and my camera is jittery
the player is a parent to the camera and when i move the camera (like rotation) it is fine but only when i start moving and rotating the camera the camera movement is very jittery
the rigidbody is interpolate, movement is in fixedUpdate as it is rigidbody movement, and cameramovement is in lateupdate
please help (tell me if you need to see any code)
Sorry, I'm not going to spoonfeed this any longer
learn some basic c# before you undertake a game at any scale
Try without interpolate
Hi, can you please send a proper screenshot? Or copy paste the full error in here.
myGameObject.transform.parent = carpet1.gameObject.transform;
this is the line of code to set the parent of "myGameObject" to "carpet1" ?
Please format it into something else other than jxr
How do you even end up with a jxr file
If you are on win 11 press WIN + Shift + S, mark the area and just do ctrl + v here
when i have the rigidbody to 'none' the camera movement is fixed but the movement of the player is a bit jittery
and with extrapolate it doesnt change anything
do you use update or fixedupate to move?
fixedupdate
oh i apparently cant read. What methods do you use to move the player?
also if you disable the camera movement itself and just keep the player movement enabled (moving the camera through parenting), does it still jitter?
it is hard to tell but yes, and when i dont move my camera, like i keep it still it does still move jittery
so there is no code affecting camera position right now? only the player being moved (and the camera following through parenting) and the camera still jitters?
are you using orthographic view?
yeah i disabled the cameramovement script and it still jitters
I think the screentoworld if for perspective, i remember having a problem but I am not 100% on that statement
What method do you use to move the player? Velocity, rb.move, transform move?
Bruhh wellif I am in perspective mode the world positio isnt changed
rb.addforce
the camera is fine right now, just the movement is jittery
but when rigidbody is on interpolate it is the other way round
wdym the other way around?
when it is on interpolate the movement is fine but the camera is jittery when i rotate it like moving my mouse
is your arena you'd like to click on an even plane?
Yea that can work
if so you can create a plane in code, and on click send a ray to your mouse cursor from the camera which then intersects with your plane and gives you a point
aH
that just tells you the build failed, is there no other output?
the rotation is done in late update? try it in normal update
I've created a canvas in which a panel with an image to become an inventory slot. When I add an image to it that's literally a square with a border I only see two sides of the border when running the game. Almost as if the camera is looking at my canvas from an angle.
Those are NOT screenshots #854851968446365696
if you make your image smaller than its original size some pixels are omitted
you can slice it to always show the border and resize the center
I must admit I forgot to resize this image now I think about it
you can just slice that image and have it any size you want
Sometimes the answer is so easy you'll never find it yourself
i tried that but it still does it.
the border will stay the same size and the center will stretch
then im out of ideas without having unity on hand rn (im on mobile) sorry
no problem thanks for atleast trying to help.
you almost fixed it with changing the rb mode to none
thanks anyways
wait, does your camera have a rb too?
Yea it is set to sliced, and I set the borders I never pressed slice tho
nope
ahh alright, hope it works then
ok good, sounded like that, one more thing, how do you rotate the camera, around the player (independently) or do you rotate the player rb?
https://gdl.space/ucurivegav.cs does anybody know why this happens? i have made this function for floor objects that can be bought. it is about the wave part in the buy function where it breaks. for some reason the refrence to the object that i want to instantiate is null??
showing the actual error and where it happens may help
oh yeah srry forgot to add the screen. its on line 128 where the print is.
Can you post the error message so we can see where it occurs? No way to tell beyond that . . .
which line is 128 in your paste? hard too see without line annotations
so hexagonPrefab is null
The reference variable on line 128 is null (not assigned) . . .
the last foreach loop
then why would the print give me a name then? because it is assigned in the inspector when i look at it.
that is reference not reference.prefab
It is within a loop. How many times does the print occur? Check the number on the right of the log . . .
obviously what you are looking at is not what the code is pointing to. So debug it
irrelevant, one exception aborts the loop
is this the reference.prefab (the prefab within the reference SO?) hard to tell with small screenshots of the inspector. just send the entire inspector so we can see . . .
i get the print as many times as the loop should run so if it runs 4 times i get it 4 times. i know that the error comes from the instantiated object but i dont know how
I would guess that you are looking at 2 or more different objects. Add an instanceid to the debug
No first of all, it was already the perfect size for the object. Also I have sliced the image borders. Yet it's still looking at it as if it's at an angle
check the compression then
there u go
dont collapse your console and look at each stack trace
Compression is high quality
point no filter I think
whats your wrap mode?
clamp
Yea I dont get it lol
hexagon.prefab is assigned to refrence.prefab. we need to see the Refrence ScriptableObject inspector, not the Hexagon script component . . .
this is what the instance id gives me
and this is the scriptable object
you need the instance id of the object causeing the null ref
what happens if you just enlarge the image object a lot?
Now it has borders on three sides
can you screenshot your slices and the result that you currently see?
oooohh i found it. whenever i call the BuyPlace function to the new hexagon the refrence isnt set yet. this confuses me tho because that means that the start isnt giving the refrence before the function is triggered?
If I move it around the canvas it will change the side where the borders show
yeah then your image has more pixels than you can show and as the border is pretty thin it gets omitted
you mean from the instantiated hex?
yeah
I'll try enlarging the border
how big is your slot image in pixels and whats your pixels per unit set to (try to play around with that value)?
honestly, your hexagon prefab should be of type Hexagon instead of GameObject. you need access to the Hexagon script, not any field of GameObject . . .
but i want to instantiate it right? or does instantiate take other stuff as well?
also, where do you set the reference for the instantiated hex? you mentioned, "the refrence isnt set yet," . . .
when you instantiate a component, the entire GameObject is instantiated, but the component is returned . . .
this avoids calling GetComponent to grab the component reference . . .
i now have made a function called GetRefrence to call out on start but also in the start of the BuyPlace function to get the refrence of the scriptable object. this is the new code: https://gdl.space/apozeyokop.cs
i didnt know this tnx. i will change it. thats gonna help a lot in the future
image object 100x100, image.png 100x100
and your pixels per unit (setting on the sprite)?
100
what happens if you change that value? play around with it a bit
It doesn't really get better, but must say making the border a bit bigger is already hella better
i mean it fixes your symptom but not the source
Oh, are you zoomed out in your editor game window maybe?
if you simulate a bigger window that it is able to display those symptoms might appear too 😄
Im not zoomed out in the game window
hmm weird 😄 my last try would be making a build to see if it still happens on fullscreen, last thing i can imagine is in-editor scaling fuckery
Think it did have to do with the scaling of the window
it was on free aspect
So I think it just did some weird things, on full screen 16:9 Im good
do you have a canvas scaler active?
if so that would be pretty normal to happen as your in-editor window is much smaller than your targeted resolution 😄
guys how can ı random ınstantıate an object ın cırcle transform area?
I wanted to say sorry to everyone for earlier as I really want to fix this issue because I've got a meeting for my new course on Monday.
There is a Random.insideUnitCircle property
Use Random.insideUnitCircle . . .
ı am looking on it now
You can also use that to write a method to instantiate between specific radii as well . . .
ı searched that but ıt says only 1 radius circle
ı mean can ı make higher or smth
Yes just multiply it by your desired radius
oh just example * 4
like that right?
Yes
okay
You have to set the size by multiplying . . .
yep
screenPosition = Input.mousePosition;
worldPosition = cam2.ScreenToWorldPoint(screenPosition);
worldPosition.y = 1000f;```
```cs
if (Input.GetMouseButtonDown (0))
{
box.transform.position = worldPosition;
}```
Trying to move a box when I click (inside of a minimap), it works but it has this very weird offset can anybody help? Using orthographic view I heard this can do stuff to it but I have no idea
you're working on an interactive map, right?
I have slots for the inventory which show the quantity and the sprite of the object but I also want to create slots that only show the name and other type of slots which only show the sprite, should I make only one component for the three or different components?
I'm guessing your problem is that [0,0] on your screen does not correspond to [0,0,0] in the world
Yes
Yup
It works and everythng its just the offset
I want it to be precisely on the mouse
If you can figure out where the bottom left and upper right corners of the map correspond to, it'd be easy enough to get the world position
I tried that but it didnt go well
I'm not exactly sure how I'd handle this, though. Haven't implemented a map before.
You could stick down two empties in the world
line them up properly manually and you'll be good to go
you can do either. mutliple components are easier because they do only what you need. when using the one component, you must have checks in place to display certain data and make sure you set up each slot to display the correct data (more room for error) . . .
I would give that another try. Show me the code you're using to find the world position if it's not working
Okay, got it, thanks!
should I implement an interface for all slots maybe?
Ok...... 😭
Also I already have a method for checking if mouse is over ui
hmm, you could. that would allow you to have one component and use the specific interface to only access the field you need . . .
maybe I´ll just make different components
yep. try one method. if that doesn't work, try the other . . .
alright, thanks!
cam2.WorldToScreenPoint(movePoint2);
Im trying but its giving me very wrong coords and also top left and bottom right only have a -2 diff
could anyone help me write a piece of code that makes an object rotate towards where my mouse is in a top down 3d game? i've tried so many things but most of them just end up pointing towards the ground or rotating in a really funky way that isnt a smooth circle around my character. thanks!
is this a 3D game? With a perspective camera?
Yes 3d No orthographic
Are you providing the appropriate Z distance?
Its a minimap trying to convert an image to real coords

How am I suppose to get that tho
You don't get it you provide it
See the diagram here
Honestly I prefer to use Plane.Raycast
it's much easier to think about
Ok wait
Vector2 localMousePosition;
RectTransformUtility.ScreenPointToLocalPointInRectangle(Minima, Input.mousePosition, null, out localMousePosition);
movePoint2 = new Vector3 (localMousePosition.x, localMousePosition.y, 10);```
Would the plane raycast work with this
This is how I move it
Yeah told him that earlier but got no Response 😅
you would do everything in world space game world coordinates
Mb I experimented withstuff
post the code you've tried and/or any errors received. we can only go based off that. if you don't have any code, i suggest starting with a tutorial (as there are many online to move or look at the mouse) . . .
What..?
How would I do everything in world space if I need to use a red dot first thats in screen space
they're trying to do a minimap. they need a way to relate a point on the minimap to a point in the world.
Do you think plane.raycast would work here?
you convert to world space, do the raycast, convert the resulting point back to canvas space
I dont see how thats helping
Thats like moving what I have rn to world space
The minimap is a visual representation of world space objects, no?
Yes
No I understand what you mean
But I also have o idea how to make it back to canvas
I also tried to do that earlier but it had a weird offset
You can convert world space to viewport point in the camera
Viewport point for the camera is a normalized 0-1. So you can use that with the rect points with https://docs.unity3d.com/ScriptReference/RectTransformUtility.PixelAdjustRect.html to get the canvas space position
Is the minimap being rendered live by cam2 in your code?
Or is it just a static image?
Okay, then it's a lot simpler
Just tried it, AGAIN has the annoying offset
I clicked inside the blue circle
Its not the same everywhere
Ray ray = cam2.ScreenPointToRay(screenPosition);
if (plane.Raycast(ray, out float distance))
{
worldPosition = ray.GetPoint(distance);
}```
It also changes if I increase the fov or not
If I use perspective still bugged
Is cam2 rendering to your entire screen, or is it rendering to a RenderTexture that you then display in a UI?
Yes render texture
Then cam2.ScreenPointToRay is not correct. You have to figure out where you clicked inside whatever is displaying the RenderTexture.
you would have to do something like:
bool clickedInMinimap = RectTransformUtility.ScreenPointToLocalPointInRectangle(myRectTransform, Input.mousePosition, mainCamera, out Vector2 viewportPoint);
if (clickedInMinimap) {
Ray r = minimapCamera.ViewportPointToRay(viewportPoint);
}```
SO USE WORLD SPACE OR SCREEN SPACE? im going crazy help
Neither. Read what Praetor wrote.
I already have a script that shows me if Im hovering over the ui
Then I just check for mouse input
The camera has no idea how you're displaying its output. It can't possibly know the size or position of your RawImage (or whatever you're using to show the render texture)
So you can't just ask it to turn a screen point into a world point
Ah
Which is why you need to do this instead.
You figure out where inside the RawImage you clicked. That gives you a viewport position for the camera. You can then convert that into a world-space ray
mainCamera player camera or minimap camera
well considering there's another variable in my example called minimapCamera...
Well yes but I dont understand why would it need player camera but okl ol
because that's the camera the UI is being drawn on
actually, if the UI is an overlay canvas, you should pass null there
Oh that makes sense
i bumped into this recently
yes was about to mention this
it's important
Just remember yea lol
Ok ill go try that
Box is not moving
bool clickedInMinimap = RectTransformUtility.ScreenPointToLocalPointInRectangle(Minima, Input.mousePosition, null, out Vector2 viewportPoint);
if (clickedInMinimap)
{
Ray r = cam.ViewportPointToRay(viewportPoint);
if (plane.Raycast(r, out float distance))
{
worldPosition = ray.GetPoint(distance);
}
}
box.transform.position = worldPosition;```
Gotcha
is there really no way to multiply a bool with a float?
well a bool is either 0 or 1
Incorrect. A bool is either true or false.
The internal representation is irrelevant.
References to these types are just a ulong, internally, but that doesn't mean you're allowed to do math with them
Now, if you want to pick between two values using a bool, you can use the conditional operator
cond ? foo : 0;
All right
can someone help me understand input system callbacks and how to use them? been reading docs and watching yt tutorials for 2 hours and dont understand why or how the " += (InputAction.CallBackContext) " is used
You're seeing someone subscribing to an event.
System.Func<int, int> add1 = (int x) => x + 1;
This syntax is used to create an anonymous function. It's a function with no name.
(int x) => x + 1; is an anonymous function that takes one argument (an int) and returns an int
InputAction has a few events on it, like performed and canceled
You can subscribe to an event by adding your function to it.
thanks a lot for the explanation, I am going to use this for what I am trying to do
someAction.performed += (InputAction.CallbackContext context) => { /* multiple lines of code can go here */ };
you can simplify that down to just
(context) => { /* ... */ }
since the type of the argument can be inferred
or even just context => { /* ... */ }
if there's only one argument, you don't need the parentheses
alright
im going to read it and tell you if i need some more assist, am i able to ping you in that case ?
So when you do this, your anonymous function will be called whenever the performed event is invoked
whatever code is inside the braces gets executed
note that you can't unsubscribe from the event if you do this
even if you use -= with an identical-looking anonymous function, that's a different anonymous function, so it won't work
but i can -= right?
I generally do this:
not because it's anonymous, but because two identical looking anonymous functions are still different
just like two functions that have the same name but are in different classes
i understand
void OnEnable() {
action.performed += HandleAction;
}
void OnDisable() {
action.performed -= HandleAction;
}
void HandleAction(InputAction.CallbackContext ctx) {
// ...
}
ty for the help im kind of new to unity and programming
I use ctx because it's short. context is also reasonable
Or even _, if you don't care about the parameter at all
That tells the compiler it's just "filler"
you can't have no parameters at all, because then HandleAction would take the wrong number of arguments.
okay let me try to read all again and see if i understand
okay i think i "understand" but i dont know how to write it, let me explain what i think it is:
what im understanding is that whenever an event happens i can susbscribe a function by adding it, InputAction has events like performed, started or canceled, but i dont know exactly how to add the function
You don't subscribe when the event happens
You subscribe once, like this.
Every time the event is invoked, HandleAction will run
Shows correct coordinates but its not detecting the mouse, the raycast is just in the middle of the camera and its not affected by mouse
!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.
If I move the camera tho, the coords are right
Red dot = middle of screen
I clicked and copy pasted the coords it gave the black circle went there 👍
https://gdl.space/yadavoqiye.cs so this should work now?
important lines are from 43 to 51
okay so let me understand it again, whenever the performed event happens it will automatically start the dash function
General rule of thumb is to always unsubscribe in the opposite of the function you subscribe in. Subscribe in OnEnable, unsub in OnDisable. Subscribe in Start, unsub in OnDestroy, etc.
without a need to tell it via code
Every function that has been subscribed to the performed event will be executed whenever the performed event is invoked.
Every time dashInput.action.performed is invoked, every function subscribed to it is called
okay
ty very much
and to subscribe to it i just need to add the (InputAction.CallBackContext ctx) after the name of the function
You need a function that takes one argument
so it doesnt throw an error
The function can be anonymous, or it can be a method.
why does it work with that argument but not with an int for example
because you can't put a round peg in a square hole
ik it sounds dumb i just want to interiorize it
performed wants a function that takes exactly one argument
the argument must have the correct type
okay let me formulate it again i think i missexplained myself
why is it inputAction.CallBackContext
what does it do
ty!
InputAction.CallbackContext is the type of thing the function is given.
CallbackContext is defined inside of InputAction
hence you refer to it as InputAction.CallbackContext
it's a nested type
public class InputAction {
public struct CallbackContext {
}
}
ViewportPointToRay wouldn't work here because thats just the center of the camera with no mouse
Imma keep researchng ty tho
there is nothing special about a mouse position
because thats just the center of the camera with no mouse
ViewportPointToRay has absolutely nothing to do with a mouse
So why can't you use it
No, what you said is that it doesn't work because there's no mouse involved
Because im using my mouse to point and click
I said it wouldnt work here because there's no mouse
Okay, so use the mouse position as your ViewportPoint to ToRayify
The function takes a positions whose values are in [0..1] and outputs a world position
RectTransformUtility.ScreenPointToLocalPointInRectangle figures out your local position in a RectTransform
I acn just do that?
ViewportPointToRay does exactly what it says on the tin. It takes a Viewport Point -> Ray
I think I see the problem, though.
If you can get a viewport point from your mouse, you can use that
Yes theres already that there
ScreenPointToLocalPointInRectangle gives you a local space position
That is not a normalized position inside the rectangle
You can use https://docs.unity3d.com/ScriptReference/Rect.PointToNormalized.html to convert the local position into a normalized position inside the rectangle
which will have values in [0..1]
Show the actual values you're getting. We haven't seen those yet.
well, you have a RectTransform...
So you ignored the part of my code that converted the mouse position into the appropriate viewport position for the minimap?
bool clickedInMinimap = RectTransformUtility.ScreenPointToLocalPointInRectangle(Minima, Input.mousePosition, null, out Vector2 viewportPoint); ?
It doesn't, though
Yes...
Yes but how do I make the point to normalized use it, doesnt work
by using this function with the rect you can fetch from your RectTransform
oh just add .rect....
I feel stupid
"Member 'Rect.PointToNormalized(Rect, Vector2)' cannot be accessed with an instance reference; qualify it with a type name instead",
Pay attention to the page I linked.
public static Vector2 PointToNormalized(Rect rectangle, Vector2 point);
This is a static method.
You don't call it on a specific Rect
I dunno what static does expect that its always there
static means that the member is part of the type, not part of a specific instance of the type
Foo myInstance = new Foo();
myInstance.Bar();
vs.
Foo.Bar();
Ah
In this case, it would be very reasonable for this to be non-static
but it isn't 🤷
Returns the normalized coordinates cooresponding the the point.
great docstring
Yea its a bit frustrating sometimes these documents dont tell me how to apply them
The function signature tells you everything you need to know, though.
Signature?
this is the signature.
It tells you the name and type of each parameter, as well as the type that gets returned
Yea its quite useful
After a bit of debugging the worldposition is 0 even tho the viewport normalized is fine, distance is fine, it gets fucked up in the raycast somewhere
ViewportPoint: (85.10, 98.09)
Normalized: (0.63, 0.65)
Distance: 19,999.99
World Position: (0, 0, 0)
bool clickedInMinimap = RectTransformUtility.ScreenPointToLocalPointInRectangle(Minima, Input.mousePosition, null, out Vector2 viewportPoint);
Debug.Log("ViewportPoint: " + viewportPoint);
Vector2 viewportPointNormalized = Rect.PointToNormalized(Minima.rect, viewportPoint);;
Debug.Log("ViewportPointNormalized: " + viewportPointNormalized);
if (clickedInMinimap)
{
Ray r = cam.ViewportPointToRay(viewportPointNormalized);
if (plane.Raycast(r, out float distance))
{
Debug.Log("Distance: " + distance);
worldPosition = ray.GetPoint(distance);
}
}
box.transform.position = worldPosition;
Debug.Log("WORLD: " + worldPosition);```
is cam the correct camera? I remember it being named cam2 last time you showed the code
This one should be the minimap camera.
Yes it is
20,000 is a very large distance. Is the minimap camera just really far away from the ground?
I made cam2 the player cam
Yes
The y is indeed 20k
I would use Debug.DrawLine to visualize this