• Advertisement
Sign in to follow this  

Unity converting Swift SpriteKit code to C# Script in Unity

This topic is 755 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I am trying to convert to following code from Swift SpriteKit to a C# Script in Unity. Coming from a SpriteKit point of view, the coordinate system in Unity is quite confusing. Basically, all I've been able to do is declare the variables. I would appreciate any assistance. Please see the code below (Swift SpriteKit):

let numberOfBlocks = 5

let blockWidth = SKSpriteNode(imageNamed: "block.png").size.width
let totalBlocksWidth = blockWidth * CGFloat(numberOfBlocks)

let padding: CGFloat = 10.0
let totalPadding = padding * CGFloat(numberOfBlocks - 1)

let xOffset = (CGRectGetWidth(frame) - totalBlocksWidth - totalPadding) / 2

for i in 0..<numberOfBlocks {
  let block = SKSpriteNode(imageNamed: "block.png")
  block.position = CGPointMake(xOffset + CGFloat(CGFloat(i) + 0.5)*blockWidth + CGFloat(i-1)*padding, CGRectGetHeight(frame) * 0.8)
  block.physicsBody = SKPhysicsBody(rectangleOfSize: block.frame.size)
  block.physicsBody!.allowsRotation = false
  block.physicsBody!.friction = 0.0
  block.physicsBody!.affectedByGravity = false
  block.name = BlockCategoryName
  block.physicsBody!.categoryBitMask = BlockCategory

Below is what I've been able to work on so far (C# Script).


void Start () {

    int numberOfBlocks = 5;
    float blockWidth = "SKSpriteNode(imageNamed: "block.png").size.width;" // How am I suppose to calculate the width of an image that I've added to the assets before I use it //GetComponent<SpriteRenderer> ().bounds.size.x;
    float totalBlocksWidth = blockWidth * numberOfBlocks;
    float padding = 10.0; // how am I suppose to represent this in Unity?
    float totalPadding = padding * (numberOfBlocks - 1);
    float camHalfHeight = Camera.main.orthographicSize;
    float xOffset = ((Camera.main.aspect * camHalfHeight) * 2 - totalBlocksWidth - totalPadding) / 2;

    for (int i = 0; i < numberOfBlocks; i++) {
        GameObject block = GameObject.CreatePrimitive(PrimitiveType.Cube);
        block.AddComponent<SpriteRenderer>().sprite = blockSprite;
        block.transform.position = new Vector2 (xOffset + (i + 0.5)*blockWidth + (i - 1)*padding, (camHalfHeight*2)*0.8 );
        block.name = "block";





  1. Where is the most appropriate place to add this script?
  2. How am I suppose to calculate the width of an image that I've added to the assets before I use it? 
  3. How do I represent CGFloat padding = 10.0 in Unity?
  4. Above I have calculated CGRectGetWidth(frame) as (Camera.main.aspect * camHalfHeight) * 2 based on a post I saw. Is there a better way to go about this calculation?

Thanks in advance.


Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement